Spring boot应用,启动Spring容器大致有如下几个过程:
容器开始启动
初始化环境变量
初始化上下文
加载上下文
完成
对应的Spring应用的启动器的监听器可以监听以上的过程,接口如下:
public interface SpringApplicationRunListener {
/**
* Called immediately when the run method has first started. Can be used for very
* early initialization.
*/
void started();
/**
* Called once the environment has been prepared, but before the
* {@link ApplicationContext} has been created.
* @param environment the environment
*/
void environmentPrepared(ConfigurableEnvironment environment);
/**
* Called once the {@link ApplicationContext} has been created and prepared, but
* before sources have been loaded.
* @param context the application context
*/
void contextPrepared(ConfigurableApplicationContext context);
/**
* Called once the application context has been loaded but before it has been
* refreshed.
* @param context the application context
*/
void contextLoaded(ConfigurableApplicationContext context);
/**
* Called immediately before the run method finishes.
* @param context the application context or null if a failure occurred before the
* context was created
* @param exception any run exception or null if run completed successfully.
*/
void finished(ConfigurableApplicationContext context, Throwable exception);
}
监听器
对应几个关键事件
监听器接口中的每个方法代表容器启动过程一个阶段,每一个阶段可以自定义执行一系列任务。可以将SpringApplicationRunListener理解成一个命令模式(传入一个对象,至于当前这个时间点,如何调用,不关心)。每一个阶段执行的序列图如下所示,其中任意方法,为SpringApplicationRunListener接口中定义的,此阶段调用的方法。
SpringApplicationRunListeners是对多个SpringApplicationRunListener做了一次代理,聚合多个SpringApplicationRunListener,在任一个过程完成,会依次调用对应方法。
private final List<SpringApplicationRunListener> listeners;
SpringApplicationRunListeners(Log log,
Collection<? extends SpringApplicationRunListener> listeners) {
this.log = log;
this.listeners = new ArrayList<SpringApplicationRunListener>(listeners);
}
public void started() {
for (SpringApplicationRunListener listener : this.listeners) {
listener.started();
}
}
public void environmentPrepared(ConfigurableEnvironment environment) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.environmentPrepared(environment);
}
}
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));
}
事件发布采用观察者模式,整个事件发布流程如下图。