Spring publishevent事件处理
spring 我们虽然经常用但是我们发现还是有很多不怎么用的功能,今天发现这么一个功能,所以决定记录下他的使用,spring源码分析的时候的再看源码,这个地方是使用的事件监听,设计模式应该是和观察者模式有关,这个地方我还没来得及看源码,先写写使用的方法吧,毕竟使用还是很简单的;
使用场景
这个一般什么时候使用,我们一般是在不同的bean直接进行信息传递,比如我们beanA的事件处理完后,需要beanB进行处理一些业务逻辑的时候这种情况就一般可以使用publish-event解决
原理
其实事件模型我们并不陌生,我们在很多地方都在用事件,事件模型当中有三个角色: 一个事件模型有三个组成部分:被监听对象source(也称为事件源),事件event和监听对象listener。
首先,由监听对象注册监听回调函数(Callback),当事件源触发了事件后,监听对象会收到事件源的信息,然后决定如何对事件源进行处理,简要流程如下图所示。
代码实现
1.先自定义事件:你的事件需要继承 ApplicationEvent
2.定义事件监听器: 需要实现 ApplicationListener
3.使用容器对事件进行发布
先定义事件:
public class OrderEvent extends ApplicationEvent { private Object object; public OrderEvent(Object source,Object t) { super(source); this.object=t; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } }
事件监听
@Component public class OrderEventListener implements ApplicationListener<OrderEvent> { @Async @Override public void onApplicationEvent(OrderEvent event) { //真正做业务的地方 try { System.out.println("开始做事"+ Thread.currentThread().getName()); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } String s = event.getObject().toString(); System.out.println("结束做事"+s); } }
事件发送
@Component public class DemoEventPublisher { @Autowired private ApplicationContext applicationContext; public void pushlish(Object o){ applicationContext.publishEvent(new OrderEvent(this,o)); } }
这个地方我是使用的java config的方式 先写个配置类,自己根据自己的方式去写就可以
@Configuration @ComponentScan("com.publishevent") public class EventConfig { }
测试类 这个地方我没有使用DemoEventPublisher 其实一样的我就是为了测试下是否可以,结果出来了 就没再改代码
public class TestEvent { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(EventConfig.class); applicationContext.publishEvent(new OrderEvent(applicationContext,"ddddd")); applicationContext.publishEvent(new OrderEvent(applicationContext,"2222")); applicationContext.publishEvent(new OrderEvent(applicationContext,"3333")); applicationContext.publishEvent(new OrderEvent(applicationContext,"444")); applicationContext.publishEvent(new OrderEvent(applicationContext,"555")); applicationContext.publishEvent(new OrderEvent(applicationContext,"666")); applicationContext.publishEvent(new OrderEvent(applicationContext,"777")); } }
效果如上