这篇笔记主要记录spring事件监听器的应用demo
在spring中,声明一个事件监听者有两种方式:
1.注解:@EventListener
2.实现ApplicationListener接口
代码
appConfig配置类
@Configuration
@ComponentScan("com.spring.publishevent")
public class AppConfig {
}
通过@EventListener注解声明一个事件监听者
@Component
public class ContextRefreshEventListener {
@EventListener(ContextRefreshedEvent.class)
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){
System.out.println("通过注解方式声明一个监听者:接收到容器启动事件");
}
}
通过实现ApplicationListener接口来声明一个事件监听者
@Component
public class ContextRefreshEventListenerInterface implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("通过实现接口声明一个事件监听者,接收到容器启动消息:");
}
}
由于我模拟监听的是spring容器启动事件,所以,只需要有下面这一行代码即可
public class EventTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
}
}