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();
}