背景
ApplicationListener是Spring事件機制的一部分,與抽象類ApplicationEvent類配合來完成ApplicationContext的事件機制。
如果容器中存在ApplicationListener的Bean,當ApplicationContext調用publishEvent方法時,對應的Bean會被觸發。這一過程是典型的觀察者模式的實現。
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 // 需對該類進行Bean的實例化
public class LearnListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 打印容器中出事Bean的數量
System.out.println("監聽器獲得容器中初始化Bean數量:" + event.getApplicationContext().getBeanDefinitionCount());
}
}
如上,便完成了一個事件監聽類的實現和實例化。
自定義事件及監聽
首先自定義事件:NotifyEvent。
public class NotifyEvent extends ApplicationEvent {
private String email;
private String content;
public NotifyEvent(Object source) {
super(source);
}
public NotifyEvent(Object source, String email, String content) {
super(source);
this.email = email;
this.content = content;
}
// 省略getter/setter方法
}
定義監聽器NotifyListener:
@Component
public class NotifyListener implements ApplicationListener<NotifyEvent> {
@Override
public void onApplicationEvent(NotifyEvent event) {
System.out.println("郵件地址:" + event.getEmail());
System.out.println("郵件內容:" + event.getContent());
}
}
監聽器通過@Component注解進行實例化,並在onApplicationEvent中打印相關信息。
單元測試類:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void testListener() {
NotifyEvent event = new NotifyEvent("object", "abc@qq.com", "This is the content");
webApplicationContext.publishEvent(event);
}
}
執行單元測試,會發現事件發布之后,監聽器方法被調用,日志被打印出來。
原文鏈接:https://www.choupangxia.com/2019/07/17/spring中applicationlistener的使用/