简介:事件机制的底层使用了观察者模式,观察者模式定义了对象间的一种一对多关系,以便当一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新,它能够将观察者和被观察者之间进行逻辑解耦,默认是同步阻塞的。
1. 事件类型
A. 上下文更新事件(ContextRefreshedEvent):ApplicationContext高级容器初始化或者刷新时触发该事件;
B. 上下文开始事件(ContextStartedEvent):当使用ConfigurableApplicationContext接口的start()方法启动ApplicationContext容器时触发该事件;
C. 上下文关闭事件(ContextClosedEvent) :当使用ConfigurableApplicationContext接口的close()方法关闭ApplicationContext容器时触发该事件;
D. 上下文停止事件(ContextStopedEvent):当使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器时触发该事件;
E. 请求处理事件(RequestHandledEvent):在Web应用中,当一个http请求结束触发该事件。
2. 举例
package com.ruhuanxingyun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.nsac.business.listener.ApplicationStartup; @SpringBootApplication public class SpApp { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(SpApp.class); springApplication.addListeners(new ApplicationStartup()); springApplication.run(args); } }
package com.nsac.ruhuanxingyun; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext ac = event.getApplicationContext(); StepExecutor StepExecutor = new StepExecutor(ac.getEnvironment().getProperty("project-id"), ac.getBean("businessSingleJedisPool",redis.clients.jedis.JedisPool.class), ac.getBean("redisCluster", redis.clients.jedis.JedisCluster.class)); Thread thread = new Thread(StepExecutor); thread.start(); } }
3. 注解
@EventListener:创建监听器并自动添加到ApplicationContext中;
4. 自定义监听器
可参考:Spring中的事件机制