代码已经上传至 https://github.com/masteryourself/study-spring.git ,分支是 master
,工程是 study-spring-framework
1. Event
1.1 ApplicationListener
-
监听容器中发布的事件,事件驱动模型开发
-
监听 ApplicationEvent 及其子类的事件
1.2 @EventListener
- 可以使用注解简化开发,原理是通过
EventListenerMethodProcessor
处理器解析方法上的@EventListener
注解
2. 代码
1. MyAnnotationListener
@Component
public class MyAnnotationListener {
@EventListener(classes = {ApplicationEvent.class})
public void applicationEventListen(ApplicationEvent event) {
System.out.println("MyAnnotationListener 接收到事件:" + event.getClass());
}
}
2. MyApplicationListener
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("MyApplicationListener 接收到事件:" + event.getClass());
}
}
3. SpringConfig
@Configuration
@ComponentScan
public class SpringConfig {
}
4. EventTest
public class EventTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
context.publishEvent(new ApplicationEvent("hello spring annotation") {
});
context.close();
// MyAnnotationListener 接收到事件:class org.springframework.context.event.ContextRefreshedEvent
// MyApplicationListener 接收到事件:class org.springframework.context.event.ContextRefreshedEvent
// MyAnnotationListener 接收到事件:class pers.masteryourself.study.spring.framework.event.EventTest$1
// MyApplicationListener 接收到事件:class pers.masteryourself.study.spring.framework.event.EventTest$1
// MyAnnotationListener 接收到事件:class org.springframework.context.event.ContextClosedEvent
// MyApplicationListener 接收到事件:class org.springframework.context.event.ContextClosedEvent
}
}
来源:CSDN
作者:masteryourself
链接:https://blog.csdn.net/masteryourself/article/details/104269114