溫故知新04-Spring之ApplicationEventPublisher

一、介紹
(1)ApplicationEventPublisherAware
ApplicationEventPublisherAware 是由 Spring 提供的用于為 Service 注入 ApplicationEventPublisher 事件發布器的接口,使用這個接口,我們自己的 Service 就擁有了發布事件的能力。
用戶注冊后,不再是顯示調用其他的業務 Service,而是發布一個用戶注冊事件。
(2)ApplicationListener
ApplicationListener接口是由 Spring 提供的事件訂閱者必須實現的接口,我們一般把該 Service 關心的事件類型作為泛型傳入。處理事件,通過 event.getSource() 即可拿到事件的具體內容
(3)ApplicationEventPublisher
ApplicationEventPublisher是ApplicationContext的父接口之一。這接口的作用是:Interface that encapsulates event publication functionality.
功能就是發布事件,也就是把某個事件告訴的所有與這個事件相關的監聽器。
二、示例
發送接口:

/**
 * @program: cz-parent
 * @description:
 * @author: shuonar
 * @create: 2021-01-14 13:30
 **/
public interface SmsService {
    void sendCode(String tel, String code);
}

實現事件發布:

/**
 * @program: cz-parent
 * @description:
 * @author: shuonar
 * @create: 2021-01-14 13:31
 **/
@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void sendCode(String tel, String code) {
        CodeDTO codeDTO = new CodeDTO(code, tel);
        applicationEventPublisher.publishEvent(codeDTO);
    }
}

訂閱:

/**
 * @program: cz-parent
 * @description: SmsEvent
 * @author: shuonar
 * @create: 2021-01-14 13:38
 **/
@Component
public class SmsEvent {
    @Async
    @EventListener
    public void handle(CodeDTO codeDTO){
        try{
            Thread.sleep(5000);
            System.out.println("監聽器接收數據---" + codeDTO.getTel() + ":" + codeDTO.getCode());

        }catch (Exception e){

        }
   }

    @Async
    @EventListener
    public void handleNone(String codeDto){
        System.out.println("監聽器接收數據---" + codeDto);

    }
}

調用:

@RequestMapping("/sendCode")
    public String sendCode(){
        SmsService smsService = this.applicationContext.getBean(SmsService.class);
        smsService.sendCode("13608236872", "111222");
        return "成功發送驗證碼";
    }

結果:

監聽器接收數據---13608236872:111222
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容