spring事件
有 事件、事件监听器、事件广播器
自定义事件
首先写一个继承了ApplicationEvent类的类 然后这个类的构造方法需要super 用来当作被监听者
public class OrderEvent extends ApplicationEvent {
private String name;
public OrderEvent(Object source, String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
}
事件监听器 基于接口
@Component public class HelloEventListener implements ApplicationListener{ @Override public void onApplicationEvent(OrderEvent event) { if(event.getName().equals("减库存")){ System.out.println("减库存......."); } } }
事件监听器 基于注解
@Component
public class OrderEventListener {
@EventListener(OrderEvent.class)
public void onApplicationEvent(OrderEvent event) {
if(event.getName().equals("减库存")){
System.out.println("减库存.......");
}
}
}
事件原型
public class Order {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
使用
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
//下单
Order order =new Order();
order.setId(1);
System.out.println("下单");
ctx.publishEvent(new OrderEvent(order,"减库存"));
System.out.println("日志...");
异步调用 理解这里看源码
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
SimpleApplicationEventMulticaster eventMulticaster
= new SimpleApplicationEventMulticaster();
//ThreadPoolTaskExecutor
eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
return eventMulticaster;
}
事件原理
spring事件监听有三个部分
事件(ApplicationEvent)负责对应相应的监听器 监听器(ApplicationListener)对应于观察者模式中的观察者 事件发布器(ApplicationEventMulticaster )对应于观察者模式中的被观察者/主题, 负责通知观察者 告诉监听器 监听那些东西
大体的思想就是 有a、b、c这三个类 a类中有aa方法 如果当我们调用了aa方法 然后b、c作为监听器(观察者)看到aa方法被调用了 那么b、c这俩类就会调用它们的监听的方法
@EventListener(OrderEvent.class)
public void onApplicationEvent(OrderEvent event) {
if(event.getName().equals("减库存")){
System.out.println("减库存.......");
}
}
比如这个方法 上面代码的监听者
ctx.publishEvent(new OrderEvent(order,“减库存”)); 这个publishEvent方法就是事件发布器 它会根据事件类型 从而决定发布给那个监听器
spring内置事件
ContextRefreshedEvent
当容器被实例化或refreshed时发布.如调用refresh()方法, 此处的实例化是指所有的bean都已被加载,后置处理器都被激活,所有单例bean都已被实例化, 所有的容器对象都已准备好可使用. 如果容器支持热重载,则refresh可以被触发多次(XmlWebApplicatonContext支持热刷新,而GenericApplicationContext则不支持) 这个在finishRefresh方法中这行publishEvent(new ContextRefreshedEvent(this));代码添加的最终还是调用onApplicationEvent方法
ContextStartedEvent
当容器启动时发布,即调用start()方法, 已启用意味着所有的Lifecycle bean都已显式接收到了start信号
ContextStoppedEvent
当容器停止时发布,即调用stop()方法, 即所有的Lifecycle bean都已显式接收到了stop信号 , 关闭的容器可以通过start()方法重启
ContextClosedEvent
当容器关闭时发布,即调用close方法, 关闭意味着所有的单例bean都已被销毁.关闭的容器不能被重启或refresh
RequestHandledEvent
这只在使用spring的DispatcherServlet时有效,当一个请求被处理完成时发布
源码图
链接:https://pan.baidu.com/s/14oJ2Z5UzZRdC72S6f-i3OQ
提取码:1234



