Spring之事件发布系统
springboot应用,启动spring容器大致有如下几个过程:
- 容器开始启动
- 初始化环境变量
- 初始化上下文
- 加载上下文
- 完成
对应的Spring应用的启动器的监听器可以监听以上的过程,接口如下:
1 public interface SpringApplicationRunListener { 2 3 /** 4 * Called immediately when the run method has first started. Can be used for very 5 * early initialization. 6 */ 7 void started(); 8 9 /** 10 * Called once the environment has been prepared, but before the 11 * {@link ApplicationContext} has been created. 12 * @param environment the environment 13 */ 14 void environmentPrepared(ConfigurableEnvironment environment); 15 16 /** 17 * Called once the {@link ApplicationContext} has been created and prepared, but 18 * before sources have been loaded. 19 * @param context the application context 20 */ 21 void contextPrepared(ConfigurableApplicationContext context); 22 23 /** 24 * Called once the application context has been loaded but before it has been 25 * refreshed. 26 * @param context the application context 27 */ 28 void contextLoaded(ConfigurableApplicationContext context); 29 30 /** 31 * Called immediately before the run method finishes. 32 * @param context the application context or null if a failure occurred before the 33 * context was created 34 * @param exception any run exception or null if run completed successfully. 35 */ 36 void finished(ConfigurableApplicationContext context, Throwable exception); 37 38 }
对应几个关键事件
监听器接口中的每个方法代表容器启动过程一个阶段,每一个阶段可以自定义执行一系列任务。可以将SpringApplicationRunListener理解成一个命令模式(传入一个对象,至于当前这个时间点,如何调用,不关心)。每一个阶段执行的序列图如下所示,其中任意方法,为SpringApplicationRunListener接口中定义的,此阶段调用的方法。
SpringApplicationRunListeners是对多个SpringApplicationRunListener做了一次代理,聚合多个SpringApplicationRunListener,在任一个过程完成,会依次调用对应方法。
1 private final List<SpringApplicationRunListener> listeners; 2 3 SpringApplicationRunListeners(Log log, 4 Collection<? extends SpringApplicationRunListener> listeners) { 5 this.log = log; 6 this.listeners = new ArrayList<SpringApplicationRunListener>(listeners); 7 } 8 9 public void started() { 10 for (SpringApplicationRunListener listener : this.listeners) { 11 listener.started(); 12 } 13 } 14 15 public void environmentPrepared(ConfigurableEnvironment environment) { 16 for (SpringApplicationRunListener listener : this.listeners) { 17 listener.environmentPrepared(environment); 18 } 19 }
SpringApplicationRunListener有一个特殊的实现EventPublishingRunListener,他的主要功能就是,在特定时间点出发特殊事件。
@Override public void started() { this.initialMulticaster.multicastEvent(new ApplicationStartedEvent( this.application, this.args)); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent( this.application, this.args, environment)); }
事件发布采用观察者模式,整个事件发布流程如下图。
没有智能的代码,源码面前了无秘密