内容简介:EventListener事件触发和监听器可以对代码解耦,在一些与业务无关的,通用的操作方法,我们可以把它设计成事件监听器,像通知,消息这些模块都可以这样设计。由于@Service也是spring组件 ,所以它里面的事件处理程序也会被注入,这时直接注入业务对象即可
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();
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Computational Advertising
by Kushal Dave、Vasudeva Varma / Now Publishers Inc / 2014
Computational Advertising (CA), popularly known as online advertising or Web advertising, refers to finding the most relevant ads matching a particular context on the Web. The context depends on the t......一起来看看 《Computational Advertising》 这本书的介绍吧!