Spring Boot 2关于ApplicationEvent的使用


ApplicationEvent与Listener是Spring提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是解耦。

自定义线程池处理

public String test1() {
    taskExecutorConfig.getAsyncExecutor().execute(() -> {
        //
    });
    return "test1";
}

将非主干逻辑放到后台线程处理,不影响主线程的业务执行时间

通过@EventListener处理

@Component
public class AnnotationRegisterListener {
	 @EventListener
    public void test2(Test1ApplicationEvent event) {
        //
    }
    @EventListener
    public void test2(Test2ApplicationEvent event) {
        //
    }
}

applicationContext().publishEvent(new Test2ApplicationEvent(this, "test2"));

通过注解方式实现对不同event的监听,不用自定义监听类

实现ApplicationListener接口自定义监听

@Component
public class Test3ApplicationListener implements ApplicationListener<Test3ApplicationEvent> {
    @Override
    public void onApplicationEvent(Test3ApplicationEvent event) {
        //
    }
}

applicationContext().publishEvent(new Test3ApplicationEvent(this, "test3"));

通过自定义监听类实现对不同event的监听

实现SmartApplicationListener接口自定义监听

@Component
public class Test4SmartApplicationListener implements SmartApplicationListener {
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == Test4ApplicationEvent.class;
    }
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return sourceType == TestServiceImpl.class;
    }
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        Test4ApplicationEvent test4ApplicationEvent = (Test4ApplicationEvent) event;       
    }
    @Override
    public int getOrder() {
        return 1;
    }
}

applicationContext().publishEvent(new Test4ApplicationEvent(this, "test4"));

SmartApplicationListener接口继承了全局监听ApplicationListener,监听所有事件发布。这里需要指定event类型以及source类型,才能精确监听到自己想要的

源码位置:
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch09

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值