• SpringBoot-关于ContextRefreshedEvent 和 ApplicationReadyEvent 触发时间以及触发机制的研究


    在日常开发里我们常常会监听ContextRefreshedEvent 以及ApplicationReadyEvent ,来做一些内容初始化的操作,因为我们通常理解为在这两类Event发生的时候,容器的bean是可用的状态,且在容器启动的过程中,这两个事件只会发生一次。然而事实真的是这样吗?它们的触发顺序又是怎么样的呢?带着疑问我们来看下SpringBoot的源码

    1. ContextRefreshedEvent 

    ContextRefreshedEvent 是spring framework所定义的事件,它的触发时间,是在容器刷新操作(refresh方法)的收尾时(finishRefresh):

    1. /**
    2. * Finish the refresh of this context, invoking the LifecycleProcessor's
    3. * onRefresh() method and publishing the
    4. * {@link org.springframework.context.event.ContextRefreshedEvent}.
    5. */
    6. protected void finishRefresh() {
    7. // Clear context-level resource caches (such as ASM metadata from scanning).
    8. clearResourceCaches();
    9. // Initialize lifecycle processor for this context.
    10. initLifecycleProcessor();
    11. // Propagate refresh to lifecycle processor first.
    12. getLifecycleProcessor().onRefresh();
    13. // Publish the final event.
    14. publishEvent(new ContextRefreshedEvent(this));
    15. // Participate in LiveBeansView MBean, if active.
    16. LiveBeansView.registerApplicationContext(this);
    17. }

    我们可以清晰地看到ContextRefreshedEvent事件的抛出;

    这里就有一个有趣的地方了,没有工程师手动执行的话,refresh方法会仅仅被调用一次,还是可能会被多次触发呢?

    这里我们可以来看一看AbstractApplicationContext的实现类

     它的直接子类有两个:AbstractRefreshableApplicationContext 以及 GenericApplicationContext;实际上,这两者都会衍生出很多容器的实现,但二者对refresh触发次数的限制是不同的;

    我们先看AbstractRefreshableApplicationContext类的介绍(部分):

    1. * Base class for {@link org.springframework.context.ApplicationContext}
    2. * implementations which are supposed to support multiple calls to {@link #refresh()},
    3. * creating a new internal bean factory instance every time.
    4. * Typically (but not necessarily), such a context will be driven by
    5. * a set of config locations to load bean definitions from.

    在第二行,我们可以看到,在这个类以及其子类中,refresh方法是可能被多次触发的!

    再来看看GenericApplicationContext:

    1. *

      In contrast to other ApplicationContext implementations that create a new

    2. * internal BeanFactory instance for each refresh, the internal BeanFactory of
    3. * this context is available right from the start, to be able to register bean
    4. * definitions on it. {@link #refresh()} may only be called once.

    在这里的第四行我们可以看到,refresh方法(可能)只会被调用到一次!

    2. ApplicationReadyEvent

    ApplicationReadyEvent是SpringBoot定义的一个事件,在SpringApplication的run方法中被调用:

    1. try {
    2. listeners.running(context);
    3. }
    4. catch (Throwable ex) {
    5. handleRunFailure(context, ex, exceptionReporters, null);
    6. throw new IllegalStateException(ex);
    7. }

    在新版本中则running方法被更换为ready方法

    1. @Override
    2. public void running(ConfigurableApplicationContext context) {
    3. context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
    4. }

    3. 总结

    ApplicationReadyEvent 是springBoot事件,只会被调用一次,在run方法的执行流程中被调用;

    ContextRefreshedEvent 可能被调用多次,如果容器是AbstractRefreshableApplicationContext的子类;(默认SpringBoot启动的容器是GenericWebApplicationContext,不是AbstractRefreshableApplicationContext的子类)

    ContextRefreshedEvent的调用在ApplicationReadyEvent之前被调用:

    1. public ConfigurableApplicationContext run(String... args) {
    2. StopWatch stopWatch = new StopWatch();
    3. stopWatch.start();
    4. ConfigurableApplicationContext context = null;
    5. Collection exceptionReporters = new ArrayList<>();
    6. configureHeadlessProperty();
    7. SpringApplicationRunListeners listeners = getRunListeners(args);
    8. listeners.starting();
    9. try {
    10. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    11. ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
    12. configureIgnoreBeanInfo(environment);
    13. Banner printedBanner = printBanner(environment);
    14. context = createApplicationContext();
    15. exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
    16. new Class[] { ConfigurableApplicationContext.class }, context);
    17. prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    18. refreshContext(context);
    19. afterRefresh(context, applicationArguments);
    20. stopWatch.stop();
    21. if (this.logStartupInfo) {
    22. new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
    23. }
    24. listeners.started(context);
    25. callRunners(context, applicationArguments);
    26. }
    27. catch (Throwable ex) {
    28. handleRunFailure(context, ex, exceptionReporters, listeners);
    29. throw new IllegalStateException(ex);
    30. }
    31. try {
    32. listeners.running(context);
    33. }
    34. catch (Throwable ex) {
    35. handleRunFailure(context, ex, exceptionReporters, null);
    36. throw new IllegalStateException(ex);
    37. }
    38. return context;
    39. }

    ContextRefreshedEvent 的调用点是 refreshContext(context);

    ApplicationReadyEvent 的调用点是 listeners.running(context);

  • 相关阅读:
    前端CSS基础10(浮动)
    requests 技术问题与解决方案:解决字典值中列表在URL编码时的问题
    SpringBoot整合Kafka (二)
    Java语法之封装
    HTTP 的前世今生
    华为十年大佬带你开启springboot实战之旅,从源码到项目,一步到位!
    Android本地数据存储(SP、SQLite、Room)
    centOS7中启动MySQL数据库提示: Failed to start mysqld.service Unit not found
    Si3262 集成低功耗SOC 三合一智能门锁应用芯片
    Spring Boot文档阅读笔记-Scheduling Tasks
  • 原文地址:https://blog.csdn.net/lhf2112/article/details/126447473