springboot~ EventListener事件监听的使用 您所在的位置:网站首页 @EventListener没有监听 springboot~ EventListener事件监听的使用

springboot~ EventListener事件监听的使用

2024-05-15 23:59| 来源: 网络整理| 查看: 265

EventListener事件触发和监听器可以对代码解耦,在一些与业务无关的,通用的操作方法,我们可以把它设计成事件监听器,像通知,消息这些模块都可以这样设计。

事件源 @Getter @Builder(toBuilder = true) public class OrderEvent { private String msg; } 事件处理程序 @Component public class OrderEventListener { @EventListener public void handleOrderEvent(OrderEvent event) { System.out.println("我监听到了handleOrderEvent发布的message为:" + event.getMsg()); } } 事件触发 @Service public class OrderService { @Autowired private ApplicationContext context; public void publishOrder() { context.publishEvent(OrderEvent.builder().msg("建立订单").build()); } } 直接测试事件处理程序 @RunWith(SpringRunner.class) @SpringBootTest public class SecurityApplicationTests implements ApplicationContextAware { private ApplicationContext context = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } @Test public void listener() { context.publishEvent(OrderEvent.builder().msg("测试方法").build()); } 测试业务代码

由于@Service也是spring组件 ,所以它里面的事件处理程序也会被注入,这时直接注入业务对象即可

@Autowired OrderService orderService; @Test public void listenerOrder() { orderService.publishOrder(); }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有