最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring的Event使用及說(shuō)明

 更新時(shí)間:2026年03月30日 09:23:29   作者:楠~楓  
本文介紹了Spring中的事件機(jī)制,包括事件的實(shí)現(xiàn)方式、推送、監(jiān)聽(tīng)器、異步事件、事件異常處理器等,并簡(jiǎn)要講述了Java自帶的觀(guān)察者模式和事件機(jī)制

1、簡(jiǎn)介

只要是事件就是觀(guān)察者模式,Spring中的Event也不例外,主要應(yīng)用就是程序解耦,實(shí)現(xiàn)本質(zhì)是廣播的形式........話(huà)不多說(shuō)

2、Spring的event實(shí)現(xiàn)方式

繼承ApplicationEvent即可,但是Spring版本4.2之后不再?gòu)?qiáng)制要求繼承ApplicationEvent,非Application的子類(lèi)將被封裝成PayloadApplicationEvent:

實(shí)現(xiàn):

import org.springframework.context.ApplicationEvent;

public class MyEvent extends ApplicationEvent {
    //todo -----  
    private String msg;

    public MyEvent(Object source) {
        super(source);
    }

    public MyEvent(Object source,String msg) {
        super(source);
        this.msg=msg;
    }

    public String getMsg() {
        return msg;
    }
}

3、事件的推送

編寫(xiě)事件推送的service實(shí)現(xiàn)ApplicationContextAwar接口,或者實(shí)現(xiàn)ApplicationEventPublisherAware接口,在需要時(shí)候根據(jù)業(yè)務(wù)場(chǎng)景推送事件:

實(shí)現(xiàn):

@Service
public class EventProduceService implements ApplicationContextAware, ApplicationEventPublisherAware {
    //實(shí)現(xiàn)方式一
    private ApplicationContext applicationContext;
    //實(shí)現(xiàn)方式二
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     *  容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
     * @param applicationEventPublisher
     */
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher=applicationEventPublisher;
    }


    /**
     * 實(shí)際業(yè)務(wù)中進(jìn)行封裝數(shù)據(jù)推送
     */
    public void sentEvent(){
        //方式一:applicationContext的推送Api可以以根據(jù)需要進(jìn)行選擇
        applicationContext.publishEvent(new MyEvent(this,"我是一顆小碼農(nóng)"));
        //方式二: applicationEventPublisher的推送Api可以以根據(jù)需要進(jìn)行選擇
        applicationEventPublisher.publishEvent(new MyEvent(this,"今天是20220804"));
    }
}

4、事件監(jiān)聽(tīng)器(處理器)

編寫(xiě)事件的處理器,交給Spring的ioc管理即可,實(shí)現(xiàn)有兩種方式,

(1)通過(guò)@EventListener注解標(biāo)注對(duì)應(yīng)的事件處理器,處理器會(huì)根據(jù)參數(shù)類(lèi)型自動(dòng)識(shí)別事件類(lèi)型的

實(shí)現(xiàn):

@Configuration
public class EventConfig {
    @EventListener
    public void doWithEvent(MyEvent myEvent) {
        System.out.println("事件消息是: "+myEvent.getMsg());
    }

   @EventListener
   public void doWithEvent(BEvent myEvent) {
       System.out.println("事件消息是: "+myEvent.getMsg());
   }

    @EventListener
    public void doWithEvent(CEvent myEvent) {
        System.out.println("事件消息是: "+myEvent.getMsg());
    }
}

(2) 實(shí)現(xiàn)ApplicationListener<T>接口,處理器會(huì)根據(jù)泛型類(lèi)型處理事件

實(shí)現(xiàn)

@Component
public class EventHandler implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        //todo----
        System.out.println(event.getMsg());
    }
}

5、異步事件

Spring默認(rèn)監(jiān)控的事件都是同步的,實(shí)現(xiàn)異步事件就需要開(kāi)啟異步事件的支持,配置類(lèi)上使用@EventListener注解開(kāi)啟異步支持,然后在監(jiān)聽(tīng)器上使用@Async注解標(biāo)注即可,同一個(gè)事件多個(gè)處理器可以使用@Order注解進(jìn)行排序(參數(shù)越小優(yōu)先級(jí)越高)

實(shí)現(xiàn):

@Configuration
@EnableAsync
public class EventConfig {
    @Async
    @EventListener
    public void doWithEvent(MyEvent myEvent) {
        System.out.println("事件消息是: "+myEvent.getMsg());
    }
}


@Async//配置類(lèi)已經(jīng)開(kāi)啟異步支持
@Component
public class EventHandler implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        //todo----
        System.out.println(event.getMsg());
    }
}

6、事件異常處理器(事件消費(fèi)方出現(xiàn)異常進(jìn)行必要處理)

(1) 同步的:

編寫(xiě)異常處理器實(shí)現(xiàn) org.springframework.util.ErrorHandler

import org.springframework.stereotype.Component;
import org.springframework.util.ErrorHandler;

//同步方式異常處理器
@Component
public class DoExphandler implements ErrorHandler {
    /**
     * 只要在SimpleApplicationEventMulticaster設(shè)置這個(gè)異常處理器,
     * 事件消費(fèi)方拋出異常就會(huì)觸發(fā)這個(gè)方法中的異常,SimpleApplicationEventMulticaster.setErrorHandler(exphandler);
     */
    @Override
    public void handleError(Throwable e) {
        if (e instanceof RuntimeException) {
            //todo
        } else {
        }
    }
}

 在SimpleApplicationEventMulticaster事件廣播中設(shè)置消費(fèi)事的異常處理器

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class EventProduceService implements ApplicationContextAware, ApplicationEventPublisherAware {
    //實(shí)現(xiàn)方式一
    private ApplicationContext applicationContext;
    //實(shí)現(xiàn)方式二
    private ApplicationEventPublisher applicationEventPublisher;

    //事件推送類(lèi)注入廣播處理同步異常
    @Autowired
    private SimpleApplicationEventMulticaster saem;

    @Autowired
    private DoExphandler exphandler;


    /**
     * 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
     *
     * @param applicationEventPublisher
     */
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }



    public void sentEvent2(Object msg) {
        applicationContext.publishEvent(new MyEvent2((String) msg));
    }


    /**
     * 設(shè)置初始化的事件異常處理器
     */
    @PostConstruct
    public void  init(){
        saem.setErrorHandler(exphandler);
    }


}

(2)異步的:

編寫(xiě)異步事件處理器異常類(lèi),實(shí)現(xiàn)AsyncUncaughtExceptionHandler接口

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Component
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable ex,
                                        Method method,
                                        Object... params) {
        //todo,做相關(guān)處理
        ex.printStackTrace();
    }
}

做異步事件異常配置:

實(shí)現(xiàn)AsyncConfigurer接口

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.Executor;

@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Autowired
    private AsyncExceptionHandler asyncExceptionHandler;

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return asyncExceptionHandler;
    }

    @Override
    public Executor getAsyncExecutor() {
        System.out.println("getAsyncExecutor");
        return AsyncConfigurer.super.getAsyncExecutor();
    }
}

7、java自帶的事件

(1)觀(guān)察者模式:

  • 作用:解耦,解耦....其他都是廢話(huà)
  • 模式工作思想:a觀(guān)察b,b做出某些動(dòng)作后,a就及時(shí)的做動(dòng)作的跟進(jìn) (至于a做啥,看你需要他做啥)
  • 設(shè)計(jì)思想:a根據(jù)b的狀態(tài)變化做出響應(yīng),一般情況下都是多個(gè)對(duì)象觀(guān)察一個(gè)對(duì)象,此時(shí)被觀(guān)察者b就需要感知到都有哪些對(duì)象在觀(guān)察自己 (設(shè)置集合存儲(chǔ)這些對(duì)象)
  • 觀(guān)察者:(在java.util.Observer已經(jīng)做了頂層接口)
public  interface  MyObserver {
  void  update(ObserverHandler handler);
}

class MyObserverImp implements MyObserver{
  private int status;

  /**
   * 根據(jù)被觀(guān)察者對(duì)象適應(yīng)自身動(dòng)作
   * @param handler 被觀(guān)察者對(duì)象
   */
  @Override
  public void update(ObserverHandler handler) {
    status=((Handler)handler).getStatus();
  }

被觀(guān)察者:(java.util. Observable已經(jīng)做了適應(yīng))

interface ObserverHandler {
    //存儲(chǔ)觀(guān)察者,感知都有那些對(duì)象在觀(guān)察
    List<MyObserver> list = new ArrayList<>();
}

class Handler implements ObserverHandler {
    private int status;

    public void setStatus(int status) {
        this.status = status;
        updateAllStatus();
    }

    public int getStatus() {
        return status;
    }

    public void updateAllStatus() {
        for (MyObserver myObserver : list) {
            myObserver.update(this);
        }
    }

    public void addObserver(MyObserver observer) {
        list.add(observer);
    }

    public void removeObserver(MyObserver observer) {
        list.remove(observer);
    }
}

(2)java的事件:

創(chuàng)建事件繼承java.util.EventObject

public class UserEvent extends EventObject {

    public UserEvent(Object source) {
        super(source);
    }
}

class SendMessageEvent extends UserEvent {

    public SendMessageEvent(Object source) {
        super(source);
    }
}

class SendFileEvent extends UserEvent {

    public SendFileEvent(Object source) {
        super(source);
    }
}

創(chuàng)建事件監(jiān)聽(tīng)器繼承:java.util.EventListener

interface UserListener extends EventListener {
    static final ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();

    void doWithEvent(UserEvent event);
}

class Listener implements UserListener {

    @Override
    public void doWithEvent(UserEvent event) {
        if (event instanceof SendFileEvent) {
            System.out.println(event);
        } else if (event instanceof SendMessageEvent) {
            System.out.println(event);
        }
    }
}

推送事件

class SendEventHandler {

    private static UserListener listener = new Listener();

    public static void main(String[] args) {
        final SendMessageEvent sentMessage = new SendMessageEvent("發(fā)送事件");
        final SendFileEvent sendFile = new SendFileEvent("發(fā)送文件");
        listener.doWithEvent(sentMessage);
        listener.doWithEvent(sendFile);
    }
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

天台县| 大悟县| 志丹县| 修文县| 墨江| 海阳市| 渭南市| 辉南县| 班戈县| 和林格尔县| 高淳县| 浦城县| 通化市| 大田县| 临颍县| 攀枝花市| 德令哈市| 河间市| 甘泉县| 东明县| 钟祥市| 赤壁市| 永丰县| 灵石县| 昌平区| 白河县| 昭通市| 博罗县| 潍坊市| 兰州市| 万荣县| 菏泽市| 铜梁县| 石景山区| 永州市| 肥城市| 黑龙江省| 巴林右旗| 财经| 万源市| 应用必备|