通过实现ApplicationListener接口创建监听器

  1. 实现ApplicationListener接口,覆写onApplicationEvent(ApplicationEvent event)方法
@Component
public class MyApplicationListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("MyApplicationListener 接收到一个事件" + event);
    }
}
  1. 通过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() 这行代码中发布

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值