工作内容

该方法会实例化所有剩余的非懒加载单例 bean。
除一些内部的 bean、实现了 BeanFactoryPostProcessor 接口的 bean、实现了 BeanPostProcessor 接口的 bean,
其他的非懒加载单例 bean 都会在这个方法中被实例化。

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. // Initialize conversion service for this context.
  3. // 注册 ConversionService
  4. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  5. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  6. beanFactory.setConversionService(
  7. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  8. }
  9. // Register a default embedded value resolver if no BeanFactoryPostProcessor
  10. // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
  11. // at this point, primarily for resolution in annotation attribute values.
  12. // 如果没有值解析器,就添加一个
  13. if (!beanFactory.hasEmbeddedValueResolver()) {
  14. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  15. }
  16. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  17. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  18. for (String weaverAwareName : weaverAwareNames) {
  19. getBean(weaverAwareName);
  20. }
  21. // Stop using the temporary ClassLoader for type matching.
  22. // 取消临时的类加载器
  23. beanFactory.setTempClassLoader(null);
  24. // bean 定义元数据不能再修改了
  25. // Allow for caching all bean definition metadata, not expecting further changes.
  26. beanFactory.freezeConfiguration();
  27. // Instantiate all remaining (non-lazy-init) singletons.
  28. // 实例化剩余的不是懒加载的单例bean
  29. beanFactory.preInstantiateSingletons();
  30. }

附件

finishBeanFactoryInitialization.drawio.zip