SpringBoot源码分析之监听器
2020-12-27 本文已影响0人
handsomemao666
1. spring监听器的设计
主要是基于发布订阅者设计模式,由广播器(MultiCaster)、事件(Event)、监听器(Listener)三个元素组成。
监听器:ApplicationListener
广播器:SpringApplicationRunListeners
事件: SpringApplicationEvent
2. spring监听器源码
SpringBoot中事件类型以及发布顺序:
- ApplicationStartingEvent : is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
- ApplicationEnvironmentPreparedEvent : is sent when the Environment to be used in the context is known but before the context is created.
- ApplicationContextInitializedEvent : is sent when the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
- ApplicationPreparedEvent : is sent just before the refresh is started but after bean definitions have been loaded.
- ApplicationStartedEvent : is sent after the context has been refreshed but before any application and command-line runners have been called.
- ApplicationReadyEvent : is sent after any application and command-line runners have been called.
- ApplicationFailedEvent : is sent if there is an exception on startup.
SpringBoot中的监听器注册:
在在/resources/META-INF新建spring.factories文件中配置监听器,通过SpringFactoriesLoader进行加载。
SpringBoot中的监听器调用:
通过SpringApplicationRunListeners在对应事件发生的时候进行广播。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}