Spring中ApplicationListener的使用


背景

  • ApplicationContext事件機制是觀察者設計模式的實現,通過ApplicationEvent類和ApplicationListener接口,可以實現ApplicationContext事件處理;
  • 如果容器中存在ApplicationListener的Bean,當ApplicationContext調用publishEvent方法時,對應的Bean會被觸發。

 spring內置事件

內置事件 描述
ContextRefreshedEvent ApplicationContext 被初始化或刷新時,該事件被觸發。這也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法來發生。此處的初始化是指:所有的Bean被成功裝載,后處理Bean被檢測並激活,所有Singleton Bean 被預實例化,ApplicationContext容器已就緒可用
ContextStartedEvent 當使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法啟動 ApplicationContext 時,該事件被發布。你可以調查你的數據庫,或者你可以在接受到這個事件后重啟任何停止的應用程序。
ContextStoppedEvent 當使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 時,發布這個事件。你可以在接受到這個事件后做必要的清理的工作。
ContextClosedEvent 當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被發布。一個已關閉的上下文到達生命周期末端;它不能被刷新或重啟。
RequestHandledEvent 這是一個 web-specific 事件,告訴所有 bean HTTP 請求已經被服務。只能應用於使用DispatcherServlet的Web應用。在使用Spring作為前端的MVC控制器時,當Spring處理用戶請求結束后,系統會自動觸發該事件。

 同樣事件可以自定義、監聽也可以自定義,完全根據自己的業務邏輯來處理。


ApplicationListener源碼

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}

ContextRefreshedEvent事件的監聽

以Spring的內置事件ContextRefreshedEvent為例,當ApplicationContext被初始化或刷新時,會觸發ContextRefreshedEvent事件,下面我們就實現一個ApplicationListener來監聽此事件的發生。

@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("容器中初始化Bean數量:" + event.getApplicationContext().getBeanDefinitionCount());
    }

}

啟動服務,可以看到

至此,便完成了一個事件及監聽類的實現和實例化。


自定義事件及監聽,以發送郵件為例

  • 自定義郵件通知事件類:EmailEvent
package com.lw.coodytest.event;

import org.springframework.context.ApplicationEvent;

/**
 * @Classname EmailEvent
 * @Description 郵件通知事件
 * @Author lw
 * @Date 2019-12-20 11:05
 */
public class EmailEvent extends ApplicationEvent {

    private String email;

    private String content;

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

    public EmailEvent(Object source, String email, String content){
        super(source);
        this.email = email;
        this.content = content;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
  • 自定義郵件通知監聽類:EmailListener
package com.lw.coodytest.listener;

import com.lw.coodytest.event.EmailEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @Classname EmailListener
 * @Description 郵件通知監聽
 * @Author lw
 * @Date 2019-12-20 11:10
 */
@Component
public class EmailListener implements ApplicationListener<EmailEvent> {

    @Override
    public void onApplicationEvent(EmailEvent emailEvent) {
        System.out.println("郵件地址:" + emailEvent.getEmail());
        System.out.println("郵件內容:" + emailEvent.getContent());
    }

}
  • 單元測試類
package com.lw.coodytest.junit;

import com.lw.coodytest.event.EmailEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

/**
 * @Classname ListenerTest
 * @Description 監聽測試類
 * @Author lw
 * @Date 2019-12-20 11:12
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {

    @Autowired
    private WebApplicationContext webapplicationcontext;

    @Test
    public void testListener(){
        EmailEvent emailEvent = new EmailEvent("object", "172572575@qq.com", "###listener");
        webapplicationcontext.publishEvent(emailEvent);
    }

}

監聽器通過@Component注解進行實例化,並在onApplicationEvent中打印相關信息

  • 執行測試類,可以看到

 至此,便完成了一個自定義事件及監聽類的實現和實例化。


 特別注意:

  不管是內置監聽還是外部自定義監聽一定要把實現ApplicationListener的類定義成一個bean才行,可以通過注解@Component或者在bean.xml中定義來實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM