1、监听器实现
实现ApplicationListener接口:
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class MyApplicationListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println("事件"+event); } }
使用@EventListener注解
import org.springframework.context.ApplicationEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class MyServiceListener { @EventListener(classes = ApplicationEvent.class) public void myService(ApplicationEvent event){ System.out.println("MyServiceListener类接收事件:"+ event); } }
2、源码解析前需要了解的事件发布工具类:ApplicationEventMulticaster接口
ApplicationEventMulticaster接口的实现类可以管理大量ApplicationListener对象并向其发布事件。
相关方法:
void addApplicationListener(ApplicationListener<?> listener); (添加一个侦听器以通知所有事件。)
void addApplicationListenerBean(String listenerBeanName);(添加一个侦听器以通知所有事件。)
void multicastEvent(ApplicationEvent event);(将给定的应用程序事件多播到适当的侦听器。)
void multicastEvent(ApplicationEvent event, ResolvableType eventType);
该工具类注入方式:refresh(); --> initApplicationEventMulticaster();
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
(APPLICATION_EVENT_MULTICASTER_BEAN_NAME=“applicationEventMulticaster”)
3、实现ApplicationListener接口方式源码解析:
1)、向ApplicationEventMulticaster接口(AbstractApplicationEventMulticaster实现类)添加实现ApplicationListener接口的监听器
refresh(); (AnnotationConfigApplicationContext.java)
registerListeners(); (AbstractApplicationContext.java)
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames){
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
2)spring框架注入的内部类:org.springframework.context.event.internalEventListenerProcessor
注入位置:
原文:https://www.cnblogs.com/yaohuiqin/p/10543846.html