谈谈你对SpringIOC的理解

谈谈你对SpringIOC的理解

什么是SpringIOC

SpringIOC中文名称翻译过来就是spring的控制反转。就是bean对象的控制权利由程序员手里移交给容器,由容器来创建对象和控制bean的生命周期,使用时只需要从容器获取就行了。举个栗子:你中午想吃饭,但是因为各种原因,你拿出手机,点开美团点了个外卖,半个小时以后外卖小哥把饭送到你的手里。这个时候我们称之为饭菜的控制权由你反转给了美团,你并不关心这个菜是哪个厨师做的,具体怎么做的,全都交给平台来处理,需要的时候由平台来提供。

 

SpringIOC的加载过程

同样的先举个栗子演示一下,假如我们去一家服装店买衣服,那么这个衣服是怎么生产最后交付给我们的

谈谈你对SpringIOC的理解

 

 

首先服装专卖店CEO创立了一家公司,并且建立了一家加工厂和存放产品的仓库,然后分别招聘了设计图管理员、产品设计师和市场调研人员。

接下来大家开始干活了,准备进行试营业:

1.首先由市场调研人员去市场上收集客户需求(当季需要什么类型的衣服,流行什么款式,有哪些常见诉求)

2.市场调研人员将收集来的样本交给产品设计师,产品设计师经过分析设计出产品设计图交给设计图管理员

3.设计图管理员拿到设计图纸放入草稿箱进行集中管理

4.代加工工厂拿到对应的设计图开始生产产品然后放入仓库

5.当客户需要什么类型的产品时,如果产品存在,则直接去仓库拿产品给客户,如果不存在,则按照需求设计和生产产品给用户

 

我们把同样的经验应用到spring容器生产bean上面再来看一遍

谈谈你对SpringIOC的理解

首先应用启动时实例化一个applicationcontext容器对象,并且创建了一个bean加工工厂DefaultListableBeanFactory和存放bean对象的仓库singletonObjects,并且分别创建了bean定义扫描器BeandefinitionScanner、bean定义阅读器BeandefinitionReader和bean定义注册器BeandifinitionRegistry

接下来大家准备开始干活了,容器准备启动了

1.首先由bean定义扫描器去扫描配置文件

2.bean定义扫描器将扫描到的配置类交给bean定义阅读器去解析,bean定义阅读器解析配置类,扫描对应包下面需要管理的类(@Component/@Service/@Controller等),将对应类的信息封装到bean定义(beandefinition)中

3.bean定义注册器将解析出来的bean定义存放到beandefinitionmap中管理起来

4.bean工厂根据读取到的bean定义来创建bean,并存入单例池中

5.需要装配对象的类获取bean的时候,如果存在,就直接从单例池中获取,否则根据bean定义创建对应对象

 

SpringIOC源码执行过程

以springboot使用的容器AnnotationConfigApplicationContext为例看一下具体执行过程。

先创建容器读取对应配置,再从容器中获取bean对象来调用,代码如下:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
User user = (User) context.getBean("user");
user.sayHello();

 

容器uml类图

谈谈你对SpringIOC的理解

代码执行流程图

谈谈你对SpringIOC的理解带参构造方法实例化容器对象

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
   this();
   register(componentClasses);
   refresh();
}

 

1.调用构造方法之前先执行父类构造方法

public GenericApplicationContext() {
   // 创建bean工厂 
   this.beanFactory = new DefaultListableBeanFactory();
}

public AbstractApplicationContext() {
   // 创建匹配路径资源解析器
   this.resourcePatternResolver = getResourcePatternResolver();
}

 

2.this构造方法

这里创建了bean定义阅读器扫描器,从uml类图上可以看出来,AnnotationConfigApplicationContext对象本身就是一个bean定义注册器

public AnnotationConfigApplicationContext() {
   StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create”);
   // 创建bean定义阅读器
   this.reader = new AnnotatedBeanDefinitionReader(this);
   createAnnotatedBeanDefReader.end();
   // 创建bean定义扫描器
   this.scanner = new ClassPathBeanDefinitionScanner(this);
}

 

2.1创建bean定义阅读器的时候,顺便往容器中注册了一些后置处理器

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
   Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
   Assert.notNull(environment, "Environment must not be null");
   this.registry = registry;
   this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
   AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

 

省略中间步骤进入最终实现,

往容器中注入了BeanFactoryPostProcessor实现类的bean定义:ConfigurationClassPostProcessor、EventListenerMethodProcessor

                       BeanPostProcessor实现类的bean定义:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor

                       默认事件监听工厂:DefaultEventListenerFactory

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
      BeanDefinitionRegistry registry, @Nullable Object source) {

   // 从上下文拿到bean工厂
   DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
   if (beanFactory != null) {
      if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
         beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
      }
      if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
         beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
      }
   }


   Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);


   if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
      def.setSource(source);
    // 往bean定义注册器(这里是实现类applicationContext)注册基础设施的bean定义,返回bean definition的包装
      beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
   }


   if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
   }


   // 检查是否需要支持JSR250注解(@Resource)如果存在使用了注解的类,往容器中添加对应后置处理器的bean定义
   // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
   if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
   }
    
   // 检查是否需要支持jpa注解,如果需要添加对应后置处理器的bean定义  
   // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
   if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition();
      try {
         def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
               AnnotationConfigUtils.class.getClassLoader()));
      }
      catch (ClassNotFoundException ex) {
         throw new IllegalStateException(
               "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
      }
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
   }


   if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
   }


   if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
      RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
      def.setSource(source);
      beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
   }


   return beanDefs;
}

 

2.2创建bean定义扫描器的时候,添加默认过滤器,默认扫描@component注解的类。

public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
      Environment environment, @Nullable ResourceLoader resourceLoader) {


   Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
   this.registry = registry;


   if (useDefaultFilters) {
      registerDefaultFilters();
   }
   setEnvironment(environment);
   setResourceLoader(resourceLoader);
}

 

3.注册配置类

使用bean定义阅读器来往容器中注入配置类的bean定义

public void register(Class<?>... componentClasses) {
   Assert.notEmpty(componentClasses, "At least one component class must be specified");
   StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register")
         .tag("classes", () -> Arrays.toString(componentClasses));
   this.reader.register(componentClasses);
   registerComponentClass.end();
}

 

这部分比较简单,先省略中间步骤,直接看最后实现

public static void registerBeanDefinition(
      BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
      throws BeanDefinitionStoreException {


   // Register bean definition under primary name.
   String beanName = definitionHolder.getBeanName();
   // 往容器中注册bean定义
   registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());


   // Register aliases for bean name, if any.
   String[] aliases = definitionHolder.getAliases();
   if (aliases != null) {
      for (String alias : aliases) {
         // 注册bean的别名
         registry.registerAlias(beanName, alias);
      }
   }
}

 

最终调用对应的bean工厂DefaultListableBeanFactory来把bean定义加进BeanDefinitionMap里面

@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
      throws BeanDefinitionStoreException {


   this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
}

 

4.refresh刷新容器

这部分内容太多,我们主要来看和springioc主流程相关的部分

synchronized (this.startupShutdownMonitor) {
   StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

   // 做一些准备工作,初始化容器状态标记,记录启动时间、验证必须属性等 
   // Prepare this context for refreshing.
   prepareRefresh();

   // 通知子类去刷新内部的bean工厂DefaultListableBeanFactory,然后返回
   // Tell the subclass to refresh the internal bean factory.
   ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

   // 准备bean工厂,添加一些后置处理器和忽略接口 
   // Prepare the bean factory for use in this context.
   prepareBeanFactory(beanFactory);


   try {
      提供给子类的扩展点,允许对内部bean工厂DefaultListableBeanFactory做一些后置处理
      // Allows post-processing of the bean factory in context subclasses.
      postProcessBeanFactory(beanFactory);

      
      StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
      // Invoke factory processors registered as beans in the context.
      // 调用bean工厂的后置处理器
      invokeBeanFactoryPostProcessors(beanFactory);


      // Register bean processors that intercept bean creation.
      // 注册拦截bean创建过程的beanPostprocessor
      registerBeanPostProcessors(beanFactory);
      beanPostProcess.end();

      // 国际化支持  
      // 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();

      // 实例化所有非懒加载的单例bean
      // 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();
      contextRefresh.end();
   }
}

 

4.1调用bean工厂后置处理器

前面我们在创建bean定义阅读器的时候,往容器的bean定义map里面注册了配置类后置处理器ConfigurationClassPostProcessor,他的类型就是BeanDefinitionRegistryPostProcessor,这里我们查出他的beanName:org.springframework.context.annotation.internalConfigurationAnnotationProcessor  

 

因为ConfigurationClassPostProcessor实现了PriorityOrdered接口,这里会优先调用beanFactory.getBean提前实例化ConfigurationClassPostProcessor

 

调用后置处理器的顺序 PriorityOrdered  BeanDefinitionRegistryPostProcessor  >  Ordered  BeanDefinitionRegistryPostProcessor >  其他 BeanDefinitionRegistryPostProcessor

 

这里我们先调用ConfigurationClassPostProcessor. postProcessBeanDefinitionRegistry方法,加载配置类,扫描和加载bean定义

           然后调用ConfigurationClassPostProcessor. postProcessBeanFactory方法,对配置类进行增强,引入bean的后置处理器 ImportAwareBeanPostProcessor

 

接下来调用 BeanFactoryPostProcessor postProcessBeanFactory方法,此时已经注册到BeanDefinitionMap中的处理器有三个:

1.propertySourcesPlaceholderConfigurer(配置源占位符解析器,用来解析配置文件,翻译占位符${},把配置文件中的属性读取到properties中)

2.org.springframework.context.event.internalEventListenerProcessor (事件监听后置处理器,把容器中的事件监听工厂取出来排序,放在事件监听处理器中)

3.ConfigurationClassPostProcessor 这个在前面的第一轮调用中已经当作BeanDefinitionRegistryPostProcessor处理过了,所以这里跳过

 

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


   // Invoke BeanDefinitionRegistryPostProcessors first, if any.
   Set<String> processedBeans = new HashSet<>();


   if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

      // 没有硬编码加入容器中的后置处理器,所以这里的空list不会执行
      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
         }
         else {
            regularPostProcessors.add(postProcessor);
         }
      }


      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();


      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      // 从bean工厂查询BeanDefinitionRegistryPostProcessor类型的后置处理器bean的名字,实际上最终就是查询BeanDefinitionMap中的bean定义
      // 前面我们在创建bean定义阅读器的时候,往容器的bean定义map里面注册了配置类后置处理器ConfigurationClassPostProcessor,他的类型就是BeanDefinitionRegistryPostProcessor,这里我们查出他的beanname
      // org.springframework.context.annotation.internalConfigurationAnnotationProcessor  
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            // 配置类后置处理器实现了PriorityOrdered接口,这里噢调用getbean方法提前实例化
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      // 处理器排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      // 回调配置类的后置处理
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
      currentRegistryProcessors.clear();


      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
         if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
      currentRegistryProcessors.clear();


      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      boolean reiterate = true;
      while (reiterate) {
         reiterate = false;
         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
         for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName)) {
               currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
               processedBeans.add(ppName);
               reiterate = true;
            }
         }
         sortPostProcessors(currentRegistryProcessors, beanFactory);
         registryProcessors.addAll(currentRegistryProcessors);
         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
         currentRegistryProcessors.clear();
      }


      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
   }


   else {
      // Invoke factory processors registered with the context instance.
      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
   }


   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let the bean factory post-processors apply to them!
   String[] postProcessorNames =
         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);


   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   for (String ppName : postProcessorNames) {
      if (processedBeans.contains(ppName)) {
         // skip - already processed in first phase above
      }
      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
         priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
      }
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
         orderedPostProcessorNames.add(ppName);
      }
      else {
         nonOrderedPostProcessorNames.add(ppName);
      }
   }


   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);


   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
   List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
   for (String postProcessorName : orderedPostProcessorNames) {
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);


   // Finally, invoke all other BeanFactoryPostProcessors.
   List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
   for (String postProcessorName : nonOrderedPostProcessorNames) {
      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);


   // Clear cached merged bean definitions since the post-processors might have
   // modified the original metadata, e.g. replacing placeholders in values...
   beanFactory.clearMetadataCache();
}

 

4.2实例化非懒加载单例bean

这一步就是bean工厂开始根据beanDefinition来生产bean的过程了

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }


   // Register a default embedded value resolver if no bean post-processor
   // (such as a PropertyPlaceholderConfigurer bean) registered any before:
   // at this point, primarily for resolution in annotation attribute values.
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }


   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }


   // Stop using the temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(null);

   // 冻结所有配置,要开始生产bean了,不允许修改bean定义了 
   // Allow for caching all bean definition metadata, not expecting further changes.
   beanFactory.freezeConfiguration();


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

调用getBean方法实例化bean对象
public void preInstantiateSingletons() throws BeansException {
   if (logger.isTraceEnabled()) {
      logger.trace("Pre-instantiating singletons in " + this);
   }


   // Iterate over a copy to allow for init methods which in turn register new bean definitions.
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);


   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      // 非抽象类 非懒加载 单例bean 开始初始化
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
         if (isFactoryBean(beanName)) {
            // 如果是factoryBean先实例化factoryBean再根据工厂方法getObject生产
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
            if (bean instanceof FactoryBean) {
               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方法实例化
            getBean(beanName);
         }
      }
   }


   // Trigger post-initialization callback for all applicable beans...
   for (String beanName : beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
         StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
               .tag("beanName", beanName);
         SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
            //回调smartSingleton的后置初始化方法
            smartSingleton.afterSingletonsInstantiated();
         }
         smartInitialize.end();
      }
   }
}

 

Do开头的才是真正干活的

protected <T> T doGetBean(
      String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
      throws BeansException {

   // 解析beanName别名 
   String beanName = transformedBeanName(name);
   Object bean;

   // 首先尝试从缓存单例池中获取,正常都是拿不到的,除非在前面手动注册进去 
   // Eagerly check singleton cache for manually registered singletons.
   Object sharedInstance = getSingleton(beanName);
   if (sharedInstance != null && args == null) {
      if (logger.isTraceEnabled()) {
         if (isSingletonCurrentlyInCreation(beanName)) {
            logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                  "' that is not fully initialized yet - a consequence of a circular reference");
         }
         else {
            logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
         }
      }
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }


   else {
      // Fail if we're already creating this bean instance:
      // We're assumably within a circular reference.
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }


      // Check if bean definition exists in this factory.
      BeanFactory parentBeanFactory = getParentBeanFactory();
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         // Not found -> check parent.
         String nameToLookup = originalBeanName(name);
         if (parentBeanFactory instanceof AbstractBeanFactory) {
            return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                  nameToLookup, requiredType, args, typeCheckOnly);
         }
         else if (args != null) {
            // Delegation to parent with explicit args.
            return (T) parentBeanFactory.getBean(nameToLookup, args);
         }
         else if (requiredType != null) {
            // No args -> delegate to standard getBean method.
            return parentBeanFactory.getBean(nameToLookup, requiredType);
         }
         else {
            return (T) parentBeanFactory.getBean(nameToLookup);
         }
      }


      if (!typeCheckOnly) {
         // 标记bean正在创建,把beanName加入名叫alreadyCreated的set中
         markBeanAsCreated(beanName);
      }


      StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
            .tag("beanName", name);
      try {
         if (requiredType != null) {
            beanCreation.tag("beanType", requiredType::toString);
         }
         // 从容器中拿到beanName对应的bean定义
         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         checkMergedBeanDefinition(mbd, beanName, args);

         // 先初始化当前bean依赖的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)) {
                // 无法解决dependOn的循环依赖
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
               }
               // 注册依赖的bean定义 
               registerDependentBean(dep, beanName);
               try {
                  // 实例化依赖bean  
                  getBean(dep);
               }
               catch (NoSuchBeanDefinitionException ex) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
               }
            }
         }


         // Create bean instance.
         if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> {
               try {
                  // 传入函数式接口ObjectFactory,最终回调这个接口来创建实例,getSingleton内部只是做了一些检查和标记,最终把创建好的单例放入单例池(一级缓存)
                  return createBean(beanName, mbd, args);
               }
               catch (BeansException ex) {
                  // Explicitly remove instance from singleton cache: It might have been put there
                  // eagerly by the creation process, to allow for circular reference resolution.
                  // Also remove any beans that received a temporary reference to the bean.
                  destroySingleton(beanName);
                  throw ex;
               }
            });
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
         }


         else if (mbd.isPrototype()) {
            // It's a prototype -> create a new instance.
            Object prototypeInstance = null;
            try {
               beforePrototypeCreation(beanName);
               prototypeInstance = createBean(beanName, mbd, args);
            }
            finally {
               afterPrototypeCreation(beanName);
            }
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         }


         else {
            String scopeName = mbd.getScope();
            if (!StringUtils.hasLength(scopeName)) {
               throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
            }
            Scope scope = this.scopes.get(scopeName);
            if (scope == null) {
               throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
            }
            try {
               Object scopedInstance = scope.get(beanName, () -> {
                  beforePrototypeCreation(beanName);
                  try {
                     return createBean(beanName, mbd, args);
                  }
                  finally {
                     afterPrototypeCreation(beanName);
                  }
               });
               bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
            }
            catch (IllegalStateException ex) {
               throw new ScopeNotActiveException(beanName, scopeName, ex);
            }
         }
      }
      catch (BeansException ex) {
         beanCreation.tag("exception", ex.getClass().toString());
         beanCreation.tag("message", String.valueOf(ex.getMessage()));
         cleanupAfterBeanCreationFailure(beanName);
         throw ex;
      }
      finally {
         beanCreation.end();
      }
   }


   // Check if required type matches the type of the actual bean instance.
   if (requiredType != null && !requiredType.isInstance(bean)) {
      try {
         T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
         if (convertedBean == null) {
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
         }
         return convertedBean;
      }
      catch (TypeMismatchException ex) {
         if (logger.isTraceEnabled()) {
            logger.trace("Failed to convert bean '" + name + "' to required type '" +
                  ClassUtils.getQualifiedName(requiredType) + "'", ex);
         }
         throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
   }
   return (T) bean;
}

 

回调createBean方法真正正式开始创建Bean

最早的第一批后置处理器InstantiationAwareBeanPostProcessor,如果这个处理器的初始化方法里面直接返回了bean对象,那么就直接使用它返回的对象,对象创建过程结束

 

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {


   if (logger.isTraceEnabled()) {
      logger.trace("Creating instance of bean '" + beanName + "'");
   }
   RootBeanDefinition mbdToUse = mbd;


   // Make sure bean class is actually resolved at this point, and
   // clone the bean definition in case of a dynamically resolved Class
   // which cannot be stored in the shared merged bean definition.
   // 解析bean class 
   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }


   // Prepare method overrides.
   try {
      // 验证Ovverride方法
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
            beanName, "Validation of method overrides failed", ex);
   }


   try {
      // 最早的第一批后置处理器InstantiationAwareBeanPostProcessor,如果这个处理器的初始化方法里面直接返回了bean对象,那么就直接使用它返回的对象,对象创建过程结束  
      // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
         return bean;
      }
   }
   catch (Throwable ex) {
      throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
            "BeanPostProcessor before instantiation of bean failed", ex);
   }


   try {
      // 其他对象通过doCreateBean方法来创建
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isTraceEnabled()) {
         logger.trace("Finished creating instance of bean '" + beanName + "'");
      }
      return beanInstance;
   }
   catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
      // A previously detected exception with proper bean creation context already,
      // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
      throw ex;
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
   }
}

 

常规bean通过doCreateBean方法来创建

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      throws BeanCreationException {


   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
      // 通过构造函数反射或者工厂方法来实例化bean对象
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   Object bean = instanceWrapper.getWrappedInstance();
   Class<?> beanType = instanceWrapper.getWrappedClass();
   if (beanType != NullBean.class) {
      mbd.resolvedTargetType = beanType;
   }


   // Allow post-processors to modify the merged bean definition.
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            // bean定义的后置处理器调用 接口名:ApplicationListenerDetector 实现类:CommonAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、ApplicationListenerDetector
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Post-processing of merged bean definition failed", ex);
         }
         mbd.postProcessed = true;
      }
   }


   // Eagerly cache singletons to be able to resolve circular references
   // even when triggered by lifecycle interfaces like BeanFactoryAware.
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isTraceEnabled()) {
         logger.trace("Eagerly caching bean '" + beanName +
               "' to allow for resolving potential circular references");
      }
      // 为了解决循环依赖,把早期实例化出来的bean(此时还没有依赖注入填充属性,也没有执行初始化方法)的引用加入三级缓存中  
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }


   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      // 注入属性
      populateBean(beanName, mbd, instanceWrapper);
      // 执行bean的初始化方法
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
   catch (Throwable ex) {
      if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
         throw (BeanCreationException) ex;
      }
      else {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
      }
   }


   if (earlySingletonExposure) {
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
         if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
         }
         else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
            String[] dependentBeans = getDependentBeans(beanName);
            Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
            for (String dependentBean : dependentBeans) {
               if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                  actualDependentBeans.add(dependentBean);
               }
            }
            if (!actualDependentBeans.isEmpty()) {
               throw new BeanCurrentlyInCreationException(beanName,
                     "Bean with name '" + beanName + "' has been injected into other beans [" +
                     StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                     "] in its raw version as part of a circular reference, but has eventually been " +
                     "wrapped. This means that said other beans do not use the final version of the " +
                     "bean. This is often the result of over-eager type matching - consider using " +
                     "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
            }
         }
      }
   }


   // Register bean as disposable.
   try {
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
   }


   return exposedObject;
}

 

Bean的依赖注入populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   // 前面已经实例化了,所以这里不为null
   if (bw == null) {
      if (mbd.hasPropertyValues()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }


   // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
   // state of the bean before properties are set. This can be used, for example,
   // to support styles of field injection.
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
         // 调用实例化通知的后置处理器,这里的三个处理器都是返回true
         if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
            return;
         }
      }
   }


   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);


   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }
      // Add property values based on autowire by type if applicable.
      if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }
      pvs = newPvs;
   }


   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);


   PropertyDescriptor[] filteredPds = null;
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
         PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
         if (pvsToUse == null) {
            if (filteredPds == null) {
               filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               return;
            }
         }
         pvs = pvsToUse;
      }
   }
   if (needsDepCheck) {
      if (filteredPds == null) {
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      // 依赖检查
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }


   if (pvs != null) {
      // 完成属性的依赖注入
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

 

Bean执行初始化 initializeBean

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      // 调用通知方法,这里只有三个BeanNameAware、BeanClassLoaderAware和BeanFactoryAware
      // 其他通知在前面通过BeanPostprocessor回调
      invokeAwareMethods(beanName, bean);
   }


   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      // 调用初始化前置方法
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }


   try {
      //调用初始化方法,包括接口回调和指定initMethod两种方式,还有一种方式解析@Postconstruct注解,在前面的后置处理器中已经初始化了  
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
   }
   if (mbd == null || !mbd.isSynthetic()) {
      // 初始化方法后置处理
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }


   return wrappedBean;
}

 

 

总结

完整的SpringIOC的加载过程和Bean的生命周期见下图,图片链接:https://processon.com/diagraming/5fec8a7b1e08532cf833f453

谈谈你对SpringIOC的理解

 

 

 

 

 

 

 

上一篇:Spring源码分析系列——bean创建过程分析(三)——工厂方法创建bean


下一篇:spring源码17: 初始化