spring容器创建源码解析

refresh()

接下来我们解析AbstractApplicationContext 中的refresh()方法源代码:

一个一个的分析refresh()中调用的各个方法

@Override
public void refresh() throws BeansException, IllegalStateException {
   
   synchronized (this.startupShutdownMonitor) {
   
      // Prepare this context for refreshing. 刷新前的预处理
      prepareRefresh();
      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);
      try {
   
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);
         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);
         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);
         // Initialize message source for this context.
         initMessageSource();
         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();
         // Initialize other special beans in specific context subclasses.
         onRefresh();
         // Check for listener beans and register them.
         registerListeners();
         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);
         // Last step: publish corresponding event.
         finishRefresh();
      }
      catch (BeansException ex) {
   
         if (logger.isWarnEnabled()) {
   
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }
         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();
         // Reset 'active' flag.
         cancelRefresh(ex);
         // Propagate exception to caller.
         throw ex;
      }
      finally {
   
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

1、prepareRefresh(); 刷新前的预处理

prepareRefresh();方法中做了如下事情

  • initPropertySources(); // 初始化一 些属性设置;子类自定义个性化的属性设置方法:
  • getEnvironment().validateRequiredProperties(); //检验属性的合法等
  • this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); //保存容器中的一些早期的事件

2、ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 获取BeanFactory

  • refreshBeanFactory(); //刷新【创建】BeanFactory
    • 创建了一个this.beanFactory = new DefaultListableBeanFactory();
    • 设置ID
  • return getBeanFactory(); //返回刚才GenericApplicationContext创建的BeanFactory对象;

3、prepareBeanFactory(beanFactory); BeanFactory的预准备工作(BeanFactory进行一些设置)

  • 设置BeanFactory的:…类加载器…支持表达式解析器…
  • 添加部分BeanPostProcessor :【Applicat ionContextAwareProcesso】
  • 设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware…;
  • 注册可以解析的自动装配;我们能直接在任何组件中自动注入:
    • BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
  • 添加BeanPostProcessor [ApplicationL istenerDetector]
  • 添加编译时的AspectJ;
  • 给BeanFactory中注册一些能用的组件;
    • environment 【ConfigurableEnvironment】
    • systemProperties 【Map<String, object>】
    • systemEnvironment 【Map<String, object>】

4、postProcessBeanFactory(beanFactory); BeanFactory 准备工作完成后进行的后置处理工作

  • 子类通过重写这个方法来在BeanF actory创建并预准备完成以后做进一步的设置

  • /** * Modify the application context's internal bean factory after its standard * initialization. All bean definitions will have been loaded, but no beans * will have been instantiated yet. This allows for registering special * BeanPostProcessors etc in certain ApplicationContext implementations. * @param beanFactory the bean factory used by the application context */
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
         
    }
    

以上是BeanFactory的创建及预备工作==

5、invokeBeanFactoryPostProcessors(beanFactory); 执行BeanFactoryPostProcessor的方法

BeanFactoryPostProcessorBeanFactory的后置处理器,在BeanFactory标准初始化之后执行

其两个接口为:BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e1O15UiM-1608261068963)(C:\Users\dell\AppData\Roaming\Typora\typora-user-images\image-20201217183336240.png)]

  • 执行BeanFactoryPostProcessor的方法

    先执行BeanDefinitionRegistryPostProcessor

    • 获取所有的BeanDefinitionRegistryPostProcessor

    • 先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor postProcessor.postProcessBeanDefinitionRegistry(registry);

    • 再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor postProcessor.postProcessBeanDefinitionRegistry(registry);

    • 最后执行没有实现任何优先级或者顺序接口的BeanDefinitionRegistryPostProcessor

      postProcessor.postProcessBeanDefinitionRegistry(registry);

    再执行BeanFactoryPostProcessor

    • 获取所有的BeanFactoryPostProcessor

    • 先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor

      postProcessor.postProcessBeanFactory(registry);

    • 再执行实现了Ordered顺序接口的BeanFactoryPostProcessor

      postProcessor.postProcessBeanFactory(registry);

    • 最后执行没有实现任何优先级或者顺序接口的BeanFactoryPostProcessor

      postProcessor.postProcessBeanFactory(registry);

6、registerBeanPostProcessors(beanFactory); 注册BeanPostProcessor(Bean的后置处理器)

不同接口类型的BeanPostProcessor,在Bean创建的前后执行时机是不一样的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vdllnkyy-1608261068969)(C:\Users\dell\AppData\Roaming\Typora\typora-user-images\image-20201217185123331.png)]

  • 获取所有的BeanPostProcessor ;后置处理器都默认可以通过Priorityordered、Ordered接口来执行优先级
  • 先注册实现PriorityOrdered优先级接口的BeanPostProcessor;
    把每一个BeanPostProcessor,添加到BeanF actory中
    beanFactory. addBeanPostProcessor( postProcessor);
  • 再注册实现Ordered接口的
  • 最后注册没有实现任何优先级接口的
  • 最终注册MergedBeanDefinitionPostProcessor
  • 注册一个ApplicationListenerDetector,在Bean创建完成后检查是否是ApplicationListener,如果是applicationContext.addApplicationListener((ApplicationListener<?>) bean);

7、initMessageSource(); 初始化MessageSource组件(做国际化功能:消息绑定、消息解析)

  • 获取BeanFactory

  • 看容器中是否有id为messageSource的,类型是MessageSource的组件

    如果有,则赋值给messageSource,如果没有自己创建一个DelegatingMessageSource;

    // Use empty MessageSource to be able to accept getMessage calls.
    DelegatingMessageSource dms = new DelegatingMessageSource();
    
    • MessageSource:取出国际化配置文件中的某个key值;能够按照区域信息获取
  • 把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;

beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);

8、initApplicationEventMulticaster(); 初始化事件派发器

  • 获取BeanFactory

  • 从BeanFactory中获取ApplicationEventMulticaster

  • 如果上一步没有配置,创建一个SimpleApplicationEventMulticaster

  • 将拆你的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入

    • this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      

9、onRefresh();留给子容器(子类)

  • 子类重写这个方法,在容器刷新的时候可以自定义逻辑;
protected void onRefresh() throws BeansException {
   
   // For subclasses: do nothing by default.
}

10、registerListeners(); 将容器中将所有项目里面的ApplicationListener注册进来;

  • 从容器中拿到所有的ApplicationL istener

    • // Register statically specified listeners first.
      for (ApplicationListener<?> listener : getApplicationListeners()) {
             
         getApplicationEventMulticaster().addApplicationListener(listener);
      }
      
  • 将每个监听器添加到事件派发器中;

    • getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
      
  • 派发之前步骤产生的事件

    • for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
             
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
      

11、finishBeanFactoryInitialization(beanFactory); 初始化所有剩下的单实例bean

  • 初始化后剩下的单实例bean

    • // Instantiate all remaining (non-lazy-init) singletons.
      beanFactory.preInstantiateSingletons();
      

    进入preInstantiateSingletons();源码 (在DefaultListableBeanFactory 中)

    DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
    • 获取容器中的所有Bean, 依次进行初始化和创建对象

    • 获取Bean的定义信息: RootBeanDefinition

    • Bean不是抽象的,是单实例的,不是懒加载;

    • List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
      // Trigger initialization of all non-lazy singleton beans...
      for (String beanName : beanNames) {
             
         RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
         if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
             
             // 判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
            if (isFactoryBean(beanName)) {
             
               Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
               if (bean instanceof FactoryBean) {
             
                  final FactoryBean<?> factory = (FactoryBean<?>) bean;
                  boolean isEagerInit;
                  if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
             
                     isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                 ((SmartFactoryBean<?>) factory)::isEagerInit,
                           getAccessControlContext());
                  }
                  else {
             
                     isEagerInit = (factory instanceof SmartFactoryBean &&
                           ((SmartFactoryBean<?>) factory).isEagerInit());
                  }
                  if (isEagerInit) {
             
                     getBean(beanName);
                  }
               }
            }
            else {
             
               // 不是工厂Bean利用getBean(beanName);创建对象
               getBean(beanName);
            }
         }
      }
      
    • 进入getBean(beanName),再进入doGetBean()方法

      • 先获取缓存中保存的单实例Bean.如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来

      • private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
        
      • 缓存中获取不到,开始Bean的创建对象流程;

      • 标记当前bean已经被创建

        if (!typeCheckOnly) {
                 
           markBeanAsCreated(beanName);
        }
        
      • 获取Bean的定义信息:

        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
        
      • 获取当前Bean依赖的其 他Bean ;如果有按照getBean( )把依赖的Bean先创建出来;

        // Guarantee initialization of beans that the current bean depends on.
        String[] dependsOn = mbd.getDependsOn();
        if (dependsOn != null) {
                 
           for (String dep : dependsOn) {
                 
              if (isDependent(beanName, dep)) {
                 
                 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                       "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
              }
              registerDependentBean(dep, beanName);
              try {
                 
                 getBean(dep);
              }
              catch (NoSuchBeanDefinitionException ex) {
                 
                 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                       "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
              }
           }
        }
        
      • 启动单实例Bean的创建流程;

        • createBean(beanName, mbd, args);
          
        • 进入AbstractAutowireCapableBeanFactory中的createBean();

          • 找到如下【让BeanPostProcessor先拦截返回代理对象】

            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            
          • @Nullable
            protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
                         
               Object bean = null;
               if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
                         
                  // Make sure bean class is actually resolved at this point.
                  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                         
                     Class<?> targetType = determineTargetType(beanName, mbd);
                     if (targetType != null) {
                         
                         //先触发
                        bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                        if (bean != null) {
                         
                           bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                        }
                     }
                  }
                  mbd.beforeInstantiationResolved = (bean != null);
               }
               return bean;
            }
            
            • 【Instanti ati onAwareBeanPostProcessor】提前执行;
            • 先触发: postProcessBeforeInstantiation( );
              如果有返回值:触发postProcessAfterInitialization( );
          • 如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;(则执行下面步骤)

          • Object beanInstance = doCreateBean(beanName, mbdToUse, args); //创建Bean
            

            doCreateBean()的方法,内容:

            • 创建Bean实例; createBeanInstance( beanName, mbd, args);

              利用工厂方法或者对象的构造器创建出Bean实例;

              if (instanceWrapper == null) {
                             
                 instanceWrapper = createBeanInstance(beanName, mbd, args);
              }
              
            • 调用MergedBeanDefinitionPostProcessors

              applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
              
              protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
                             
                 for (BeanPostProcessor bp : getBeanPostProcessors()) {
                             
                    if (bp instanceof MergedBeanDefinitionPostProcessor) {
                             
                       MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                       //这里
                       bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
                    }
                 }
              }
              
          • 【Bean属性赋值】 populateBean( beanName, mbd, instanceWrapper);

            赋值之前:

            • 拿到InstantiationAwareBeanPostProcessor后置处理器

              进行:postProcessAfterInstantiation();

            • 拿到InstantiationAwareBeanPostProcessor后置处理器

              进行:postProcessPropertyValues();

              上面赋值之前=====

            • 应用Bean属性的值;为属性利用setter方法等进行赋值;

              if (pvs != null) {
                             
                 applyPropertyValues(beanName, mbd, bw, pvs);
              }
              
          • 【Bean初始化】initializeBean( beanName, exposedobject, mbd) ;

            • 【执行Aware接口方法】invokeAwareMethods ( beanName, bean) ;执行xXxAware接口的方法

              BeanNameAware \ BeanClassLoaderAwareBeanFactoryAware

            • 【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

              BeanPostProcessor.postProcessBeforeInitialization () ;

            • 【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);

              • 是否是InitializingBean接口的实现;执行接口规定的初始化;
              • 是否自定义初始化方法:
            • 【执行后置处理器初始化之后】applyBeanPostProcessorsAfterInitialization

              BeanPostProcessor . postProcessAfterInitialization( );

          • 注册Bean的销毁方法

      • 将创建的Bean添加到缓存中singletonObjects;

        ioc容器就是这些Map:很多的Map里面保存了单实例Bean,环境信息。。。。;

    • 所有Bean都利用getBean创建完成之后

      检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();

      // Trigger post-initialization callback for all applicable beans...
      for (String beanName : beanNames) {
             
         Object singletonInstance = getSingleton(beanName);
         if (singletonInstance instanceof SmartInitializingSingleton) {
             
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
             
               AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
             
                   // 。。。。。。。。。。。这里执行。。。。。。。。。。。。。。
                  smartSingleton.afterSingletonsInstantiated();
                  return null;
               }, getAccessControlContext());
            }
            else {
             
               smartSingleton.afterSingletonsInstantiated();
            }
         }
      }
      

    12、finishRefresh(); 完成BeanFactory的初始化创建工作; IOC容器就创建完成;

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);
}
  • initLifecycleProcessor(); 初始化和生命周期有关的后置处理器(LifecycleProcessor):

    • 默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;

    • 如果没有就DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); 然后加到容器中

    • 可以自定义实现LifecycleProcessor接口

      public interface LifecycleProcessor extends Lifecycle {
             
         /** * Notification of context refresh, e.g. for auto-starting components. */
         void onRefresh();
         /** * Notification of context close phase, e.g. for auto-stopping components. */
         void onClose();
      }
      
  • getLifecycleProcessor().onRefresh(); 拿到前面定义的生命周期处理器(BeanFactory) ;回调onRefresh( );

  • publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件

  • LiveBeansView.registerApplicationContext(this); 如果处于活动状态,添加到LiveBeansView MBean

总结

  • Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息;

    • xml注册bean;
    • 注解注册Bean; @Service. @Component、@Bean. xxx
  • Spring容器会合适的时机创建这些Bean

    • 用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中;
    • 统一创建剩下所有的bean的时候; finishBeanFactoryInitialization();
  • 后置处理器; BeanPostProcessor

    • 每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;

      Autowi redAnnotationBeanPostProcessor :处理自动注入
      AnnotationAwareAspectJAutoProxyCreator :来做AOP功能;
      XXx…
      增强的功能注解:
      AsyncAnnotationBeanPostProcessor

  • 事件驱动模型;

    • ApplicationListener;事件监听;
    • ApplicationEventMulticaster;事件派发:
张贴在2