ApplicationContext用于扩展BeanFactory功能,面向用户使用

  1. public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
  2. this(new String[] {configLocation}, true, null);
  3. }
  4. public ClassPathXmlApplicationContext(
  5. String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
  6. throws BeansException {
  7. super(parent);
  8. setConfigLocations(configLocations);
  9. if (refresh) {
  10. refresh();
  11. }
  12. }
  1. 设置配置路径
    1. 这一步还会解析 ${xx}内容
  2. 执行refresh()

    1. @Override
    2. public void refresh() throws BeansException, IllegalStateException {
    3. synchronized (this.startupShutdownMonitor) {
    4. StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
    5. // Prepare this context for refreshing.
    6. prepareRefresh();
    7. // Tell the subclass to refresh the internal bean factory.
    8. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    9. // Prepare the bean factory for use in this context.
    10. prepareBeanFactory(beanFactory);
    11. try {
    12. // Allows post-processing of the bean factory in context subclasses.
    13. postProcessBeanFactory(beanFactory);
    14. StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
    15. // Invoke factory processors registered as beans in the context.
    16. invokeBeanFactoryPostProcessors(beanFactory);
    17. // Register bean processors that intercept bean creation.
    18. registerBeanPostProcessors(beanFactory);
    19. beanPostProcess.end();
    20. // Initialize message source for this context.
    21. initMessageSource();
    22. // Initialize event multicaster for this context.
    23. initApplicationEventMulticaster();
    24. // Initialize other special beans in specific context subclasses.
    25. onRefresh();
    26. // Check for listener beans and register them.
    27. registerListeners();
    28. // Instantiate all remaining (non-lazy-init) singletons.
    29. finishBeanFactoryInitialization(beanFactory);
    30. // Last step: publish corresponding event.
    31. finishRefresh();
    32. }
    33. catch (BeansException ex) {
    34. if (logger.isWarnEnabled()) {
    35. logger.warn("Exception encountered during context initialization - " +
    36. "cancelling refresh attempt: " + ex);
    37. }
    38. // Destroy already created singletons to avoid dangling resources.
    39. destroyBeans();
    40. // Reset 'active' flag.
    41. cancelRefresh(ex);
    42. // Propagate exception to caller.
    43. throw ex;
    44. }
    45. finally {
    46. // Reset common introspection caches in Spring's core, since we
    47. // might not ever need metadata for singleton beans anymore...
    48. resetCommonCaches();
    49. contextRefresh.end();
    50. }
    51. }
    52. }
    1. 初始化前的准备工作,系统、环境变量进行准备及验证
    2. 初始化BeanFactory,并进行XML文件读取
    3. 对BeanFactory进行各种功能填充,@Autowired就是在这步增加支持
    4. 子类覆盖方法做额外处理,让其子类实现一些方法
    5. 激活各种BeanFactory处理器
    6. 注册拦截bean创建的bean处理器,这里只是注册BeanPostProcessor
    7. 为上下文初始化Message源,国际化
    8. 初始化消息广播器,放入applicationEventMulticaster的bean中
    9. 留给子类来初始化其他的bean
    10. 查找listenerbean,注册到消息广播器中
    11. 初始化剩下的单实例
    12. 完成刷新过程,通知生命周期处理器lifecycleProcessor

      环境准备prepareRefresh()

      1. protected void prepareRefresh() {
      2. // 记录启动日期
      3. this.startupDate = System.currentTimeMillis();
      4. this.closed.set(false);
      5. this.active.set(true);
      6. if (logger.isDebugEnabled()) {
      7. if (logger.isTraceEnabled()) {
      8. logger.trace("Refreshing " + this);
      9. }
      10. else {
      11. logger.debug("Refreshing " + getDisplayName());
      12. }
      13. }
      14. // Initialize any placeholder property sources in the context environment.
      15. // 实例化 占位符属性 留给子类实现
      16. initPropertySources();
      17. // Validate that all properties marked as required are resolvable:
      18. // see ConfigurablePropertyResolver#setRequiredProperties
      19. // 验证所有的属性文件在环境中
      20. getEnvironment().validateRequiredProperties();
      21. // Store pre-refresh ApplicationListeners...
      22. if (this.earlyApplicationListeners == null) {
      23. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
      24. }
      25. else {
      26. // Reset local application listeners to pre-refresh state.
      27. this.applicationListeners.clear();
      28. this.applicationListeners.addAll(this.earlyApplicationListeners);
      29. }
      30. // Allow for the collection of early ApplicationEvents,
      31. // to be published once the multicaster is available...
      32. this.earlyApplicationEvents = new LinkedHashSet<>();
      33. }

      加载BeanFactory

      ```java protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); }

  1. @Override
  2. protected final void refreshBeanFactory() throws BeansException {
  3. if (hasBeanFactory()) {
  4. destroyBeans();
  5. closeBeanFactory();
  6. }
  7. try {
  8. DefaultListableBeanFactory beanFactory = createBeanFactory();
  9. beanFactory.setSerializationId(getId());
  10. customizeBeanFactory(beanFactory);
  11. loadBeanDefinitions(beanFactory);
  12. this.beanFactory = beanFactory;
  13. }
  14. catch (IOException ex) {
  15. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  16. }
  17. }
  18. @Override
  19. public final ConfigurableListableBeanFactory getBeanFactory() {
  20. DefaultListableBeanFactory beanFactory = this.beanFactory;
  21. if (beanFactory == null) {
  22. throw new IllegalStateException("BeanFactory not initialized or already closed - " +
  23. "call 'refresh' before accessing beans via the ApplicationContext");
  24. }
  25. return beanFactory;
  26. }
  1. 分析`refreshBeanFactory()`方法
  2. 1. 创建`DefaultListableBeanFactory`
  3. 2. 指定序列化id
  4. 3. 定制`BeanFactory`
  5. 4. 加载`BeanDefinition`
  6. 5. 使用全局变量记录`BeanFactory`
  7. <a name="OOzS8"></a>
  8. ## 定制BeanFactory
  9. ```java
  10. protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
  11. if (this.allowBeanDefinitionOverriding != null) {
  12. beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
  13. }
  14. if (this.allowCircularReferences != null) {
  15. beanFactory.setAllowCircularReferences(this.allowCircularReferences);
  16. }
  17. }
  1. 设置是否允许相同名的BeanDefinition覆盖
  2. 设置是否允许循环依赖

    加载BeanDefinition

    1. @Override
    2. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    3. // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    4. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    5. // Configure the bean definition reader with this context's
    6. // resource loading environment.
    7. beanDefinitionReader.setEnvironment(this.getEnvironment());
    8. beanDefinitionReader.setResourceLoader(this);
    9. beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
    10. // Allow a subclass to provide custom initialization of the reader,
    11. // then proceed with actually loading the bean definitions.
    12. initBeanDefinitionReader(beanDefinitionReader);
    13. loadBeanDefinitions(beanDefinitionReader);
    14. }

    功能补充prepareBeanFactory

    1. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    2. // Tell the internal bean factory to use the context's class loader etc.
    3. beanFactory.setBeanClassLoader(getClassLoader());
    4. if (!shouldIgnoreSpel) {
    5. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    6. }
    7. beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    8. // Configure the bean factory with context callbacks.
    9. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    10. beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    11. beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    12. beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    13. beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    14. beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    15. beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    16. beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
    17. // BeanFactory interface not registered as resolvable type in a plain factory.
    18. // MessageSource registered (and found for autowiring) as a bean.
    19. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    20. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    21. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    22. beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    23. // Register early post-processor for detecting inner beans as ApplicationListeners.
    24. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    25. // Detect a LoadTimeWeaver and prepare for weaving, if found.
    26. if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
    27. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
    28. // Set a temporary ClassLoader for type matching.
    29. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    30. }
    31. // Register default environment beans.
    32. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
    33. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    34. }
    35. if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
    36. beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    37. }
    38. if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
    39. beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    40. }
    41. if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
    42. beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
    43. }
    44. }
  3. 增加对SpEL语言的支持

  4. 增加对属性编辑器的支持
  5. 增加一些内置类
  6. 设置依赖功能可忽略接口
  7. 注册一些固定的依赖竖向
  8. 增加AspectJ支持
  9. 相关环境变量及属性注册以单例模式注册

    增加SpEL支持

    ```java
    1. if (!shouldIgnoreSpel) {
    2. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    3. }
  1. public StandardBeanExpressionResolver(@Nullable ClassLoader beanClassLoader) {
  2. this.expressionParser = new SpelExpressionParser(new SpelParserConfiguration(null, beanClassLoader));
  3. }
  1. SpEL能在运行时构建复杂表达式、存取对象图属性、对象方法调用等。<br />SpEL使用`#{}`作为定界符
  2. <a name="BJZ5w"></a>
  3. ## 增加属性注册编辑器
  4. Spring DI注入的时候可以把普通属性注入进来,但是`Date`之类的是无法直接注入的,于是我盟可以自定义属性编辑器
  5. <a name="uiVY9"></a>
  6. ### 使用自定义属性编辑器
  7. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/1609516/1655716890328-c6c59786-077e-471c-9301-862bb38d2564.png#clientId=u3c547e1f-ca4e-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=731&id=u4818c6a6&margin=%5Bobject%20Object%5D&name=image.png&originHeight=731&originWidth=936&originalType=binary&ratio=1&rotation=0&showTitle=false&size=108337&status=done&style=none&taskId=uecf4096b-0ba1-47c0-afea-04e48c9d978&title=&width=936)<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/1609516/1655717199449-c19a55eb-4560-4a0a-bb6a-50f9efd639bf.png#clientId=u3c547e1f-ca4e-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=529&id=uaece7d2a&margin=%5Bobject%20Object%5D&name=image.png&originHeight=529&originWidth=949&originalType=binary&ratio=1&rotation=0&showTitle=false&size=58815&status=done&style=none&taskId=u9eab8504-510b-4e5a-b286-5137f84f5cc&title=&width=949)
  8. <a name="AGOPt"></a>
  9. ### 注册Spring自带的属性编辑器
  10. <a name="oYqKs"></a>
  11. ## 添加ApplicationContextAwareProcessor处理器
  12. ```java
  13. class ApplicationContextAwareProcessor implements BeanPostProcessor {
  14. private final ConfigurableApplicationContext applicationContext;
  15. private final StringValueResolver embeddedValueResolver;
  16. /**
  17. * Create a new ApplicationContextAwareProcessor for the given context.
  18. */
  19. public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
  20. this.applicationContext = applicationContext;
  21. this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
  22. }
  23. @Override
  24. @Nullable
  25. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  26. if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
  27. bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
  28. bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
  29. bean instanceof ApplicationStartupAware)) {
  30. return bean;
  31. }
  32. AccessControlContext acc = null;
  33. if (System.getSecurityManager() != null) {
  34. acc = this.applicationContext.getBeanFactory().getAccessControlContext();
  35. }
  36. if (acc != null) {
  37. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  38. invokeAwareInterfaces(bean);
  39. return null;
  40. }, acc);
  41. }
  42. else {
  43. invokeAwareInterfaces(bean);
  44. }
  45. return bean;
  46. }
  47. }

设置忽略依赖

一般是提出Aware类的依赖注入,因为在之前已经注入过了

注册依赖

注册这些后,一旦有这些类的依赖就立即将指定实例注入

BeanFactory的后处理

BeanFactoryPostProcessor对BeanFactory进行一些处理

激活注册的BFPP

可以注册多个BeanFactoryPostProcessor,设置order属性。Spring中存在对于BeanFactoryPostProcessor的典型应用,比如PropertyPlaceholderConfigurer

典型应用

PropertyPlaceholderConfigurer

自定义

  1. 定义类继承
  2. 注册bean

    激活BeanFactoryPostProcessor

    ```java protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {

    1. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    2. // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
    3. // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
    4. if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
    5. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
    6. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    7. }

    }

public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

  1. // WARNING: Although it may appear that the body of this method can be easily
  2. // refactored to avoid the use of multiple loops and multiple lists, the use
  3. // of multiple lists and multiple passes over the names of processors is
  4. // intentional. We must ensure that we honor the contracts for PriorityOrdered
  5. // and Ordered processors. Specifically, we must NOT cause processors to be
  6. // instantiated (via getBean() invocations) or registered in the ApplicationContext
  7. // in the wrong order.
  8. //
  9. // Before submitting a pull request (PR) to change this method, please review the
  10. // list of all declined PRs involving changes to PostProcessorRegistrationDelegate
  11. // to ensure that your proposal does not result in a breaking change:
  12. // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
  13. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  14. Set<String> processedBeans = new HashSet<>();
  15. if (beanFactory instanceof BeanDefinitionRegistry) {
  16. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  17. List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  18. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
  19. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  20. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  21. BeanDefinitionRegistryPostProcessor registryProcessor =
  22. (BeanDefinitionRegistryPostProcessor) postProcessor;
  23. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  24. registryProcessors.add(registryProcessor);
  25. }
  26. else {
  27. regularPostProcessors.add(postProcessor);
  28. }
  29. }
  30. // Do not initialize FactoryBeans here: We need to leave all regular beans
  31. // uninitialized to let the bean factory post-processors apply to them!
  32. // Separate between BeanDefinitionRegistryPostProcessors that implement
  33. // PriorityOrdered, Ordered, and the rest.
  34. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
  35. // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  36. String[] postProcessorNames =
  37. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  38. for (String ppName : postProcessorNames) {
  39. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  40. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  41. processedBeans.add(ppName);
  42. }
  43. }
  44. sortPostProcessors(currentRegistryProcessors, beanFactory);
  45. registryProcessors.addAll(currentRegistryProcessors);
  46. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  47. currentRegistryProcessors.clear();
  48. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  49. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  50. for (String ppName : postProcessorNames) {
  51. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  52. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  53. processedBeans.add(ppName);
  54. }
  55. }
  56. sortPostProcessors(currentRegistryProcessors, beanFactory);
  57. registryProcessors.addAll(currentRegistryProcessors);
  58. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  59. currentRegistryProcessors.clear();
  60. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  61. boolean reiterate = true;
  62. while (reiterate) {
  63. reiterate = false;
  64. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  65. for (String ppName : postProcessorNames) {
  66. if (!processedBeans.contains(ppName)) {
  67. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  68. processedBeans.add(ppName);
  69. reiterate = true;
  70. }
  71. }
  72. sortPostProcessors(currentRegistryProcessors, beanFactory);
  73. registryProcessors.addAll(currentRegistryProcessors);
  74. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  75. currentRegistryProcessors.clear();
  76. }
  77. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  78. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  79. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  80. }
  81. else {
  82. // Invoke factory processors registered with the context instance.
  83. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  84. }
  85. // Do not initialize FactoryBeans here: We need to leave all regular beans
  86. // uninitialized to let the bean factory post-processors apply to them!
  87. String[] postProcessorNames =
  88. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  89. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  90. // Ordered, and the rest.
  91. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  92. List<String> orderedPostProcessorNames = new ArrayList<>();
  93. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  94. for (String ppName : postProcessorNames) {
  95. if (processedBeans.contains(ppName)) {
  96. // skip - already processed in first phase above
  97. }
  98. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  99. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  100. }
  101. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  102. orderedPostProcessorNames.add(ppName);
  103. }
  104. else {
  105. nonOrderedPostProcessorNames.add(ppName);
  106. }
  107. }
  108. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  109. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  110. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  111. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  112. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  113. for (String postProcessorName : orderedPostProcessorNames) {
  114. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  115. }
  116. sortPostProcessors(orderedPostProcessors, beanFactory);
  117. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  118. // Finally, invoke all other BeanFactoryPostProcessors.
  119. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  120. for (String postProcessorName : nonOrderedPostProcessorNames) {
  121. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  122. }
  123. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  124. // Clear cached merged bean definitions since the post-processors might have
  125. // modified the original metadata, e.g. replacing placeholders in values...
  126. beanFactory.clearMetadataCache();
  127. }
  1. > 暂时没看懂
  2. <a name="iBzMx"></a>
  3. # 注册BeanPostProcessor
  4. <a name="eViWP"></a>
  5. # 初始化消息资源
  6. <a name="hrMNk"></a>
  7. # 初始化ApplicationEventMulticaster
  8. 一定是用于存放监听器并在合适的时候调用监听器,<br />`SimpleApplicationEventMulticaster`
  9. <a name="NFPX0"></a>
  10. # 注册监听器
  11. 将监听器加入广播器中
  12. <a name="Bnwvi"></a>
  13. # 初始化非延迟加载单例
  14. ```java
  15. /**
  16. * Finish the initialization of this context's bean factory,
  17. * initializing all remaining singleton beans.
  18. */
  19. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  20. // Initialize conversion service for this context.
  21. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  22. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  23. beanFactory.setConversionService(
  24. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  25. }
  26. // Register a default embedded value resolver if no BeanFactoryPostProcessor
  27. // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
  28. // at this point, primarily for resolution in annotation attribute values.
  29. if (!beanFactory.hasEmbeddedValueResolver()) {
  30. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  31. }
  32. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  33. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  34. for (String weaverAwareName : weaverAwareNames) {
  35. getBean(weaverAwareName);
  36. }
  37. // Stop using the temporary ClassLoader for type matching.
  38. beanFactory.setTempClassLoader(null);
  39. // Allow for caching all bean definition metadata, not expecting further changes.
  40. beanFactory.freezeConfiguration();
  41. // Instantiate all remaining (non-lazy-init) singletons.
  42. beanFactory.preInstantiateSingletons();
  43. }
  1. ConversionService的配置
  2. 冻结配置,配置不能再让修改了
  3. 初始化非延迟加载类

    1. @Override
    2. public void preInstantiateSingletons() throws BeansException {
    3. if (logger.isTraceEnabled()) {
    4. logger.trace("Pre-instantiating singletons in " + this);
    5. }
    6. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    7. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    8. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    9. // Trigger initialization of all non-lazy singleton beans...
    10. for (String beanName : beanNames) {
    11. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    12. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    13. if (isFactoryBean(beanName)) {
    14. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
    15. if (bean instanceof FactoryBean) {
    16. FactoryBean<?> factory = (FactoryBean<?>) bean;
    17. boolean isEagerInit;
    18. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
    19. isEagerInit = AccessController.doPrivileged(
    20. (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
    21. getAccessControlContext());
    22. }
    23. else {
    24. isEagerInit = (factory instanceof SmartFactoryBean &&
    25. ((SmartFactoryBean<?>) factory).isEagerInit());
    26. }
    27. if (isEagerInit) {
    28. getBean(beanName);
    29. }
    30. }
    31. }
    32. else {
    33. getBean(beanName);
    34. }
    35. }
    36. }
    37. // Trigger post-initialization callback for all applicable beans...
    38. for (String beanName : beanNames) {
    39. Object singletonInstance = getSingleton(beanName);
    40. if (singletonInstance instanceof SmartInitializingSingleton) {
    41. StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
    42. .tag("beanName", beanName);
    43. SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
    44. if (System.getSecurityManager() != null) {
    45. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    46. smartSingleton.afterSingletonsInstantiated();
    47. return null;
    48. }, getAccessControlContext());
    49. }
    50. else {
    51. smartSingleton.afterSingletonsInstantiated();
    52. }
    53. smartInitialize.end();
    54. }
    55. }
    56. }

    循环getBean

finishRefresh()

initLifecycleProcessor

初始化生命周期Processor

  1. protected void initLifecycleProcessor() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. // 会找一个 lifecycleProcessor的bean存在则用我的,不存在走else用默认的
  4. if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
  5. this.lifecycleProcessor =
  6. beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
  9. }
  10. }
  11. else {
  12. DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
  13. defaultProcessor.setBeanFactory(beanFactory);
  14. this.lifecycleProcessor = defaultProcessor;
  15. beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
  16. if (logger.isTraceEnabled()) {
  17. logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
  18. "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
  19. }
  20. }
  21. }

onRefresh

调用生命周期类的onfresh方法

publishEvent

发布一个ContextRefreshedEvent 事件