- 实现ApplicationListener接口,覆写onApplicationEvent(ApplicationEvent event)方法
@Component
public class MyApplicationListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("MyApplicationListener 接收到一个事件" + event);
}
}
- 通过IOC容器发布事件
@Configuration
@ComponentScan(value = {"com.dgr.spring.application_listener"})
public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainClass.class);
context.publishEvent(new ApplicationEvent("发布一个事件") {
@Override
public Object getSource() {
return super.getSource();
}
});
context.close();
}
}
当然,这里也可以通过继承 ApplicationEvent 抽象类 来实现自定义事件
3. 查看控制台输出
21:03:08.537 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'mainClass'
21:03:08.542 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myApplicationListener'
MyApplicationListener 接收到一个事件org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@18eed359, started on Mon Dec 02 21:03:08 GMT+08:00 2019]
MyApplicationListener 接收到一个事件com.dgr.spring.application_listener.MainClass$1[source=发布一个事件]
21:03:08.589 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@18eed359, started on Mon Dec 02 21:03:08 GMT+08:00 2019
MyApplicationListener 接收到一个事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@18eed359, started on Mon Dec 02 21:03:08 GMT+08:00 2019]
这里接受到了三个事件,处理中间的事件是我们自己发布的外,他两个事件都是Spring IOC 容器发布的事件:
ContextRefreshedEvent: 容器刷新事件
ContextClosedEvent:容器关闭事件,如果在我们的MainClass的main函数中的 context.close() 这行代码中发布