在日常开发里我们常常会监听ContextRefreshedEvent 以及ApplicationReadyEvent ,来做一些内容初始化的操作,因为我们通常理解为在这两类Event发生的时候,容器的bean是可用的状态,且在容器启动的过程中,这两个事件只会发生一次。然而事实真的是这样吗?它们的触发顺序又是怎么样的呢?带着疑问我们来看下SpringBoot的源码:
1. ContextRefreshedEvent
ContextRefreshedEvent 是spring framework所定义的事件,它的触发时间,是在容器刷新操作(refresh方法)的收尾时(finishRefresh):
- /**
- * Finish the refresh of this context, invoking the LifecycleProcessor's
- * onRefresh() method and publishing the
- * {@link org.springframework.context.event.ContextRefreshedEvent}.
- */
- protected void finishRefresh() {
- // Clear context-level resource caches (such as ASM metadata from scanning).
- clearResourceCaches();
-
- // Initialize lifecycle processor for this context.
- initLifecycleProcessor();
-
- // Propagate refresh to lifecycle processor first.
- getLifecycleProcessor().onRefresh();
-
- // Publish the final event.
- publishEvent(new ContextRefreshedEvent(this));
-
- // Participate in LiveBeansView MBean, if active.
- LiveBeansView.registerApplicationContext(this);
- }
我们可以清晰地看到ContextRefreshedEvent事件的抛出;
这里就有一个有趣的地方了,没有工程师手动执行的话,refresh方法会仅仅被调用一次,还是可能会被多次触发呢?
这里我们可以来看一看AbstractApplicationContext的实现类

它的直接子类有两个:AbstractRefreshableApplicationContext 以及 GenericApplicationContext;实际上,这两者都会衍生出很多容器的实现,但二者对refresh触发次数的限制是不同的;
我们先看AbstractRefreshableApplicationContext类的介绍(部分):
- * Base class for {@link org.springframework.context.ApplicationContext}
- * implementations which are supposed to support multiple calls to {@link #refresh()},
- * creating a new internal bean factory instance every time.
- * Typically (but not necessarily), such a context will be driven by
- * a set of config locations to load bean definitions from.
在第二行,我们可以看到,在这个类以及其子类中,refresh方法是可能被多次触发的!
再来看看GenericApplicationContext:
- *
In contrast to other ApplicationContext implementations that create a new
- * internal BeanFactory instance for each refresh, the internal BeanFactory of
- * this context is available right from the start, to be able to register bean
- * definitions on it. {@link #refresh()} may only be called once.
在这里的第四行我们可以看到,refresh方法(可能)只会被调用到一次!
2. ApplicationReadyEvent
ApplicationReadyEvent是SpringBoot定义的一个事件,在SpringApplication的run方法中被调用:
- try {
- listeners.running(context);
- }
- catch (Throwable ex) {
- handleRunFailure(context, ex, exceptionReporters, null);
- throw new IllegalStateException(ex);
- }
在新版本中则running方法被更换为ready方法
- @Override
- public void running(ConfigurableApplicationContext context) {
- context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
- }
3. 总结
ApplicationReadyEvent 是springBoot事件,只会被调用一次,在run方法的执行流程中被调用;
ContextRefreshedEvent 可能被调用多次,如果容器是AbstractRefreshableApplicationContext的子类;(默认SpringBoot启动的容器是GenericWebApplicationContext,不是AbstractRefreshableApplicationContext的子类)
ContextRefreshedEvent的调用在ApplicationReadyEvent之前被调用:
- public ConfigurableApplicationContext run(String... args) {
- StopWatch stopWatch = new StopWatch();
- stopWatch.start();
- ConfigurableApplicationContext context = null;
- Collection
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;
- }
ContextRefreshedEvent 的调用点是 refreshContext(context);
ApplicationReadyEvent 的调用点是 listeners.running(context);