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));
}
事件發布采用觀察者模式,整個事件發布流程如下圖。
Spring Boot+Nginx+Tomcat+SSL配置筆記 http://www.linuxidc.com/Linux/2016-01/127134.htm
Spring Boot 的詳細介紹:請點這裡
Spring Boot 的下載地址:請點這裡