Spring源码解析之bean的实例化

Spring IOC源码解析

动态修改BeanDefinition

xml解析完毕,调用AbstractApplicationContext#invokeBeanFactoryPostProcessors进行BeanDefinition的动态修改,主要是完成BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的调用

// BeanDefinitionRegistryPostProcessor调用
// BeanFactoryPostProcessor调用
invokeBeanFactoryPostProcessors()
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
   // ...
}

接下来我们看一下这个非常臃肿的方法,不知道spring为什么能够写出这么臃肿的代码。。主要步骤:收集BeanDefinitionRegistryPostProcessor实现类,按照实现PriorityOrdered、Ordered或无实现排序接口进行分类,然后按照PriorityOrdered->Ordered->无实现排序接口的顺序进行调用(invokeBeanDefinitionRegistryPostProcessors)。其中,ConfigurationClassPostProcessor这个类实现了BeanDefinitionRegistryPostProcessor,会被调用,里面的代码很重要,我们后面再讲!

接着收集BeanFactoryPostProcessor实现类,最后会调用postProcessBeanFactory方法。处理逻辑和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<>();

			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<>();

			// 收集同时实现BeanDefinitionRegistryPostProcessor和PriorityOrdered接口的类
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { 
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			//排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			//调用。其中ConfigurationClassPostProcessor这个类会被调用,这个类非常非常重要!后面再讲
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

      // 收集同时实现BeanDefinitionRegistryPostProcessor和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);
			currentRegistryProcessors.clear();

			// 收集实现BeanDefinitionRegistryPostProcessor且不实现任何排序接口的类
			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);
				currentRegistryProcessors.clear();
			}

			//调用postProcessBeanFactory方法
			// 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
			}
			//实现了PriorityOrdered接口的
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			//实现了Ordered接口的
			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();
	}

调用BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry

private static void invokeBeanDefinitionRegistryPostProcessors(
      Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

   for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
      postProcessor.postProcessBeanDefinitionRegistry(registry);
   }
}

调用BeanFactoryPostProcessor.postProcessBeanFactory

private static void invokeBeanFactoryPostProcessors(
      Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

   for (BeanFactoryPostProcessor postProcessor : postProcessors) {
      postProcessor.postProcessBeanFactory(beanFactory);
   }
}

注册BeanPostProcessor

AbstractApplicationContext#registerBeanPostProcessors,这个方法会收集所有实现BeanPostProcessor的类,并提前实例化。常见的BeanPostProcessor有AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor

/*
 * 把实现了BeanPostProcessor接口的类实例化,并且加入到BeanFactory中
 * */
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    // 收集实现BeanPostProcessor的类
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		//提前实例化BeanPostProcessor类型的bean,然后bean进行排序
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// getBean是实例化方法,先别看,后面我们在讲bean实例化过程会着重讲
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				//判断类型是否是MergedBeanDefinitionPostProcessor,如果是则代码是内部使用的
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		//注册到BeanFactory中
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

Bean实例化

实例化过程

AbstractApplicationContext#finishBeanFactoryInitialization,Spring最重要的方法!

/*
 * 这个方法是spring中最重要的方法,没有之一
 * 所以这个方法一定要理解要具体看
 * 1、bean实例化过程
 * 2、ioc
 * 3、注解支持
 * 4、BeanPostProcessor的执行
 * 5、Aop的入口
 * */
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
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));
   }
   // ...

   //重点看这个方法,重要程度:5
   // Instantiate all remaining (non-lazy-init) singletons.
   beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException {
   // ...
   // xml解析时,讲过,把所有beanName都缓存到beanDefinitionNames了
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
      //把父BeanDefinition里面的属性拿到子BeanDefinition中
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      //如果是非抽象的,单例的,非懒加载的就实例化
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
         //判断bean是否实现了FactoryBean接口
         if (isFactoryBean(beanName)) {
            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 {
            //主要从这里进入,看看实例化过程
            getBean(beanName);
         }
      }
   }
	 // ...
}

走getBean方法

public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}

先从缓存取,如果不存在,就创建。期间会进行父子BeanDefinition的合并,还有依赖对象的实例化,依赖对象的实例化会遍历所有依赖对象,然后getBean分别进行依赖对象的实例化。接下来我们主要看createBean方法

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

   String beanName = transformedBeanName(name);
   Object bean;

   // 从缓存中拿实例,这里我们简单看下就行,循环依赖会有更详尽的解析
   Object sharedInstance = getSingleton(beanName);
   //如果缓存里面能拿到实例
   if (sharedInstance != null && args == null) {
      // ...
      //该方法是FactoryBean接口的调用入口
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }

   else {
      // 如果singletonObjects缓存里面没有,则走下来
      // 如果是scope 是Prototype的,校验是否有出现循环依赖,如果有则直接报错
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }
      // ...
      try {
         //父子BeanDefinition合并
         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         checkMergedBeanDefinition(mbd, beanName, args);

         // 获取依赖对象属性,依赖对象要先实例化
         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);
               }
            }
         }

         // 着重看,大部分是单例的情况
         if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> { // 查看getSingleton方法,这里对理解循环依赖有帮助
               try {
                  // 走这里,创建bean
                  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;
               }
            });
            // 该方法是FactoryBean接口的调用入口
            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);
            }
            //该方法是FactoryBean接口的调用入口
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         }
   // ..
   // ..
   return (T) bean;
}

getSingleton的流程捋一下:首先从一级缓存获取bean,拿到了就直接返回;拿不到,先把当前bean放入正在实例化bean的集合中(以前以为这就是常说的二级缓存,其实不是🤔),然后进行bean的实例化(包括依赖注入),实例化完成后,从正在实例化bean的集合中删除,然后把实例化后的bean放到一级缓存。

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
   Assert.notNull(beanName, "Bean name must not be null");
   synchronized (this.singletonObjects) {
      //如果缓存中有,则直接返回
      Object singletonObject = this.singletonObjects.get(beanName);
      if (singletonObject == null) {
         if (this.singletonsCurrentlyInDestruction) {
            throw new BeanCreationNotAllowedException(beanName,
                  "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                  "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
         }
         if (logger.isDebugEnabled()) {
            logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
         }
         //把beanName添加到singletonsCurrentlyInCreation Set容器中,在这个集合里面的bean都是正在实例化的bean(未di)
         beforeSingletonCreation(beanName);
         boolean newSingleton = false;
         boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
         if (recordSuppressedExceptions) {
            this.suppressedExceptions = new LinkedHashSet<>();
         }
         try {
            // 如果这里有返回值,就代表这个bean已经结束创建了,已经完全创建成功
            singletonObject = singletonFactory.getObject();
            newSingleton = true;
         }
         // ...
         finally {
            if (recordSuppressedExceptions) {
               this.suppressedExceptions = null;
            }
            //bean创建完成后singletonsCurrentlyInCreation要删除该bean
            afterSingletonCreation(beanName);
         }
         if (newSingleton) {
            //创建对象成功时,把对象缓存到singletonObjects缓存中,bean创建完成时放入一级缓存
            addSingleton(beanName, singletonObject);
         }
      }
      return singletonObject;
   }
}

进行bean的实例化,走createBean方法,继续跟进到doCreateBean方法

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

   //...

   try {
      /*
       * TargetSource接口的运用,可以在用改一个类实现该接口,然后在里面定义实例化对象的方式,然后返回
       * 也就是说不需要spring帮助我们实例化对象
       * */
      // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
         return bean;
      }
   }
   //...
   try {
      //主要看这个方法
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
   //...
}

跟进走createBeanInstance方法

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) {
      //创建实例,,重点看,重要程度:5
      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 {
            //CommonAnnotationBeanPostProcessor  支持了@PostConstruct,@PreDestroy,@Resource注解
            //AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解
            //BeanPostProcessor接口的典型运用,这里要理解这个接口
            //对类中注解的装配过程
            //重要程度5,必须看。这块后面讲PostProcessor时会详细讲。
            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.
   //是否单例bean提前暴露
   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");
      }
      //这里着重理解,对理解循环依赖帮助非常大,重要程度 5。这块后面讲
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
      //ioc di,依赖注入的核心方法,该方法必须看,重要程度:5
      populateBean(beanName, mbd, instanceWrapper);
      //bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
   //...

   // Register bean as disposable.
   try {
      //注册bean销毁时的类DisposableBeanAdapter
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   //...

   return exposedObject;
}

接着我们走createBeanInstance方法,然后走instantiateBean方法,进行无参构造函数的实例化,这里我们不看了,它只是简单的通过反射去实例化bean

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   //...

   //如果有FactoryMethodName属性 @Bean的实现。这个以后再看
   if (mbd.getFactoryMethodName() != null) {
      return instantiateUsingFactoryMethod(beanName, mbd, args);
   }
   // ...

   // Candidate constructors for autowiring?
   //寻找当前正在实例化的bean中有@Autowired注解的构造函数。以后再看
   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
   if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      //如果ctors不为空,就说明构造函数上有@Autowired注解
      return autowireConstructor(beanName, mbd, ctors, args);
   }

   // Preferred constructors for default construction?
   ctors = mbd.getPreferredConstructors();
   if (ctors != null) {
      return autowireConstructor(beanName, mbd, ctors, null);
   }

   //无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化
   // No special handling: simply use no-arg constructor.
   return instantiateBean(beanName, mbd);
}

到这里Bean实例化大致的脉络就讲完了,实例化完成后就可以进行DI依赖注入了。在这之前,把我们在实例化过程中的一些比较重要的点先讲下。

通过FactoryBean实例化类

FactoryBean可以帮助我们实现类的实例化,我们可以看到MyFactoryBeanService这个类并没有@Component之类的注解,说明它是通过MyFactoryBean去创建的。那么我们来欣赏下spring是如何处理FactoryBean的。

@Component
public class MyFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        // getObject方法,实例化了MyFactoryBeanService类
        return new MyFactoryBeanService();
    }

    @Override
    public Class<?> getObjectType() {
        // getObjectType设置Bean的类型
        return MyFactoryBeanService.class;
    }
}
public class MyFactoryBeanService {

    public void test() {
        System.out.println("factoryBean测试类");
    }
}

我们看下DefaultListableBeanFactory#preInstantiateSingletons这个方法,首先判断Bean是否实现了FactoryBean接口,然后就去实例化FactoryBean类(通过&beanName的形式去获取,如果不加&,表示获取的是FactorrBean#getObject()方法里面返回的对象。)

public void preInstantiateSingletons() throws BeansException {
   // ...
         if (isFactoryBean(beanName)) {
            // 判断bean是否实现了FactoryBean接口,如果走进来,说明当前bean实现了FactoryBean接口
            // 调用getBean方法,这里会去实例化myFactoryBean,注意这里beanNam加了&前缀,加&表示获取的是FactoryBean这个Bean,不加&表示获取的是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);
               }
            }
         }
        //...
}

getBean方法前面讲Bean实例化的时候已经讲解过,就不细讲了。我们主要看getObjectForBeanInstance

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

  // 我们知道name是带有&的,这里把它转换为不带&前缀
   String beanName = transformedBeanName(name);
   Object bean;
  // ...
         //着重看,大部分是单例的情况
         // Create bean instance.
         if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> {
               try {
                  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;
               }
            });
            //该方法是FactoryBean接口的调用入口
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
         }

继续走getObjectForBeanInstance

protected Object getObjectForBeanInstance(
      Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

   String currentlyCreatedBean = this.currentlyCreatedBean.get();
   if (currentlyCreatedBean != null) {
      registerDependentBean(beanName, currentlyCreatedBean);
   }

   return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
}

这个方法就是BeanFactory接口的调用了。

protected Object getObjectForBeanInstance(
			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

		if (BeanFactoryUtils.isFactoryDereference(name)) { // 如果name是&开头的,直接返回。
			if (beanInstance instanceof NullBean) {
				return beanInstance;
			}
			if (!(beanInstance instanceof FactoryBean)) {
				throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
			}
			if (mbd != null) {
				mbd.isFactoryBean = true;
			}
			return beanInstance;
		}

		// Now we have the bean instance, which may be a normal bean or a FactoryBean.
		// If it's a FactoryBean, we use it to create a bean instance, unless the
		// caller actually wants a reference to the factory.
		//如果实例不是FactoryBean类型的
		if (!(beanInstance instanceof FactoryBean)) {
			return beanInstance;
		}

		//如果代码能走下来,则说明 beanName不是以&开头,并且beanInstance是FactoryBean类型的
		Object object = null;
		if (mbd != null) {
			mbd.isFactoryBean = true;
		}
		else {
			//从缓存里面拿FactoryBean类型的实例
			object = getCachedObjectForFactoryBean(beanName);
		}
		if (object == null) {
			// Return bean instance from factory.
			FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
			// Caches object obtained from FactoryBean if it is a singleton.
			if (mbd == null && containsBeanDefinition(beanName)) {
				mbd = getMergedLocalBeanDefinition(beanName);
			}
			boolean synthetic = (mbd != null && mbd.isSynthetic());
			// 如果不存在,那么调用getObjectFromFactoryBean去获取
			object = getObjectFromFactoryBean(factory, beanName, !synthetic);
		}
		return object;
	}

走getObjectFromFactoryBean方法看下代码,主要两个操作,一,调用factorybean的getObject方法;二,把factorybean存到factoryBeanObjectCache中,注意,这里name是factorybean的名称,而value是factorybean.getObject返回的对象。

protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
   if (factory.isSingleton() && containsSingleton(beanName)) {
      synchronized (getSingletonMutex()) {
         Object object = this.factoryBeanObjectCache.get(beanName);
         if (object == null) {
            //调用getObject方法
            object = doGetObjectFromFactoryBean(factory, beanName);
            // Only post-process and store if not put there already during getObject() call above
            // (e.g. because of circular reference processing triggered by custom getBean calls)
            Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
            if (alreadyThere != null) {
               object = alreadyThere;
            }
            else {
               // ...
               if (containsSingleton(beanName)) {
                  //把实例缓存到factoryBeanObjectCache map中,这个实例是factorybean.getObject返回的对象。
                  this.factoryBeanObjectCache.put(beanName, object);
               }
            }
         }
         return object;
      }
   }
   //...
}

getObjectFromFactoryBean,这个方法主要是调用factoryBean实现类的getObject方法。

private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
   Object object;
   try {
      if (System.getSecurityManager() != null) {
         AccessControlContext acc = getAccessControlContext();
         try {
            object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
         }
         catch (PrivilegedActionException pae) {
            throw pae.getException();
         }
      }
      else {
         // 调用factorybean实现类的getObject方法
         object = factory.getObject();
      }
   }
   //...
   return object;
}
FactoryMethodName属性的应用(@Bean的实现原理)

通过设置FactoryMethodName属性也可以实现Bean的实例化,@Bean的原理其实是,spring扫描所有@Bean标注的方法,然后把它设置成factoryMethodName属性。spring为我们提供了两种FactoryName的设置方式,一种是使用静态方法实例化,另一种使用非静态方法去实例化。其中,非静态方法需要提供factoryBean属性,指向的是调用哪个类的工厂方法。以以下例子来说,静态方法和非静态方法都会实例化MyFactoryStaticService对象。

<!-- 静态方法 -->
<bean id="myStaticMethod" class="com.cbl.init.factorymethod.MyFactoryMethod"
      factory-method="getStaticService"/>
<!-- 非静态方法 -->
<bean id="myFactoryMethod" class="com.cbl.init.factorymethod.MyFactoryMethod"/>
    <bean id="getMyFactoryMethodService" factory-bean="myFactoryMethod" factory-method="getMyFactoryMethodService"/>
</bean>
public class MyFactoryMethod {

    // 静态方法
    public static MyFactoryStaticService getStaticService() {
        return new MyFactoryStaticService();
    }

    // 非静态方法
    public MyFactoryMethodService getMyFactoryMethodService() {
        return new MyFactoryMethodService();
    }
}

那么我们来分析下源码,AbstractAutowireCapableBeanFactory#createBeanInstance

//如果有FactoryMethodName属性 @Bean
if (mbd.getFactoryMethodName() != null) {
   return instantiateUsingFactoryMethod(beanName, mbd, args);
}
rotected BeanWrapper instantiateUsingFactoryMethod(
      String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {

   return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}

大概流程就是拿到factory-bean属性,判断是静态还是非静态方法,最后通过反射去调用工厂方法,略。

public BeanWrapper instantiateUsingFactoryMethod(
      String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {

   BeanWrapperImpl bw = new BeanWrapperImpl();
   this.beanFactory.initBeanWrapper(bw);

   Object factoryBean;
   Class<?> factoryClass;
   boolean isStatic;

   //获取factoryBean name,即factory-bean属性
   String factoryBeanName = mbd.getFactoryBeanName();
   if (factoryBeanName != null) {
      // factory-bean存在,说明非静态方法
      if (factoryBeanName.equals(beanName)) {
         throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
               "factory-bean reference points back to the same bean definition");
      }
      factoryBean = this.beanFactory.getBean(factoryBeanName);
      if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
         throw new ImplicitlyAppearedSingletonException();
      }
      factoryClass = factoryBean.getClass();
      //factoryMethod要为非静态方法
      isStatic = false;
   }
   else {
      // factory-bean不存在,说明静态方法
      // It's a static factory method on the bean class.
      if (!mbd.hasBeanClass()) {
         throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
               "bean definition declares neither a bean class nor a factory-bean reference");
      }
      factoryBean = null;
      factoryClass = mbd.getBeanClass();
      //factoryMethod需要为静态方法
      isStatic = true;
   }
// ...后面代码略
有参构造函数注入

这里其实也算是依赖注入的范畴了,依赖注入主要有两种写法,一是我们常用的@Autowired修饰成员变量,二是使用有参构造函数进行属性的注入。Spring官方是非常推荐使用第二种方式的。那么我们看下它的源码,AbstractAutowireCapableBeanFactory#createBeanInstance

//寻找当前正在实例化的bean中有@Autowired注解的构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
      mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
   //如果ctors不为空,就说明构造函数上有@Autowired注解
   return autowireConstructor(beanName, mbd, ctors, args);
}

遍历所有实现SmartInstantiationAwareBeanPostProcessor接口的PostProcessor,然后我们通过断点找到了AutowiredAnnotationBeanPostProcessor类,调用该类的determineCandidateConstructors方法去收集@Autowired修饰的构造方法。

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
      throws BeansException {

   if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
            SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
            Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
            if (ctors != null) {
               return ctors;
            }
         }
      }
   }
   return null;
}

我们看下AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors,又是一个又臭又长的方法,其实就是干这件事,收集bean类里面的所有构造方法,筛选出@Autowired标注的构造方法,然后返回一个集合。

public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
      throws BeanCreationException {
	 // ...

   // Quick check on the concurrent map first, with minimal locking.
   Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
   if (candidateConstructors == null) {
      // Fully synchronized resolution now...
      synchronized (this.candidateConstructorsCache) {
         candidateConstructors = this.candidateConstructorsCache.get(beanClass);
         if (candidateConstructors == null) {
            Constructor<?>[] rawCandidates;
            try {
               //获取bean对应的所有构造器
               rawCandidates = beanClass.getDeclaredConstructors();
            }
            catch (Throwable ex) {
               throw new BeanCreationException(beanName,
                     "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                     "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
            }
            List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
            Constructor<?> requiredConstructor = null;
            Constructor<?> defaultConstructor = null;
            Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
            int nonSyntheticConstructors = 0;
            for (Constructor<?> candidate : rawCandidates) {
               if (!candidate.isSynthetic()) {
                  nonSyntheticConstructors++;
               }
               else if (primaryConstructor != null) {
                  continue;
               }
               //获取到构造函数上的@Autowired注解信息,这个方法可以不看
               MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
               if (ann == null) {
                  Class<?> userClass = ClassUtils.getUserClass(beanClass);
                  if (userClass != beanClass) {
                     try {
                        Constructor<?> superCtor =
                              userClass.getDeclaredConstructor(candidate.getParameterTypes());
                        ann = findAutowiredAnnotation(superCtor);
                     }
                     catch (NoSuchMethodException ex) {
                        // Simply proceed, no equivalent superclass constructor found...
                     }
                  }
               }
               if (ann != null) {
                  if (requiredConstructor != null) {
                     throw new BeanCreationException(beanName,
                           "Invalid autowire-marked constructor: " + candidate +
                           ". Found constructor with 'required' Autowired annotation already: " +
                           requiredConstructor);
                  }
                  //获取到@Autowired里面的required方法的值
                  boolean required = determineRequiredStatus(ann);
                  if (required) {
                     if (!candidates.isEmpty()) {
                        throw new BeanCreationException(beanName,
                              "Invalid autowire-marked constructors: " + candidates +
                              ". Found constructor with 'required' Autowired annotation: " +
                              candidate);
                     }
                     requiredConstructor = candidate;
                  }
                  candidates.add(candidate);
               }
               else if (candidate.getParameterCount() == 0) {
                  defaultConstructor = candidate;
               }
            }
            //...
      }
   }
   return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

我们拿到带@Autowired的构造函数,再去调用AbstractAutowireCapableBeanFactory#autowireConstructor方法

protected BeanWrapper autowireConstructor(
      String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {

   return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}

autowireConstructor方法的代码很长,这里省略了很多,其实主要就是遍历所有构造函数,拿到构造函数的参数,然后对参数进行实例化操作。

public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
      @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {

  	  //...
      for (Constructor<?> candidate : candidates) {
         int parameterCount = candidate.getParameterCount();

         //如果之前的构造器已经有一个被处理过,则后面的构造器就不用处理了
         if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
            // Already found greedy constructor that can be satisfied ->
            // do not look any further, there are only less greedy constructors left.
            break;
         }
         if (parameterCount < minNrOfArgs) {
            continue;
         }

         ArgumentsHolder argsHolder;
         Class<?>[] paramTypes = candidate.getParameterTypes();
         if (resolvedValues != null) {
            try {
               String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
               if (paramNames == null) {
                  ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                  if (pnd != null) {
                     paramNames = pnd.getParameterNames(candidate);
                  }
               }
               //这里会触发构造函数中参数的getBean操作,会实例化参数的值
               argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                     getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
            }
            //...
   return bw;
}
循环依赖

循环依赖就是两个bean互相依赖注入对方的过程。理解循环依赖的关键是理解三级缓存。我们举个例子: A依赖B,B依赖A。我们先看源码,待会再做总结。

入口:AbstractAutowireCapableBeanFactory#doCreateBean

首先进行A的实例化,主要步骤是添加三级缓存,删除二级缓存

// 是否单例bean提前暴露,主要就是判断当前正在实例化bean集合中有没有。如果允许提前暴露,则添加三级缓存
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");
   }
   //这里着重理解,对理解循环依赖帮助非常大,重要程度 5   添加三级缓存
   addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

添加三级缓存,如果一级缓存不存在,设置三级缓存,删除二级缓存

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
   Assert.notNull(singletonFactory, "Singleton factory must not be null");
   synchronized (this.singletonObjects) {
      //如果一级缓存不存在
      if (!this.singletonObjects.containsKey(beanName)) {
         //设置三级缓存
         this.singletonFactories.put(beanName, singletonFactory);
         //删除二级缓存
         this.earlySingletonObjects.remove(beanName);
         this.registeredSingletons.add(beanName);
      }
   }
}

接下来进行A的依赖注入,由于依赖的是B,所以调用getBean去获取B,B重复A的实例化过程,也是设置三级缓存,删除二级缓存。

接下来就是B的依赖注入,依赖了A,调用getBean去获取A,这个时候注意了,getSingleton是可以拿到A的缓存的!

AbstractBeanFactory#doGetBean

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

   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 + "'");
         }
      }
      //该方法是FactoryBean接口的调用入口
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }
  // ...
  return (T) bean;
}

这个时候B从缓存拿A,发现在第三级缓存中已经存在了A,就把A升级到二级缓存,并删除。

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
   //根据beanName从缓存中拿实例
   //先从一级缓存拿
   Object singletonObject = this.singletonObjects.get(beanName);
   //如果bean还正在创建,还没创建完成,其实就是堆内存有了,属性还没有DI依赖注入
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
         //从二级缓存中拿
         singletonObject = this.earlySingletonObjects.get(beanName);
         //如果还拿不到,并且允许bean提前暴露
         if (singletonObject == null && allowEarlyReference) {
            //从三级缓存中拿到对象工厂
            ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
            if (singletonFactory != null) {
               //从工厂中拿到对象
               singletonObject = singletonFactory.getObject();
               //升级到二级缓存
               this.earlySingletonObjects.put(beanName, singletonObject);
               //删除三级缓存
               this.singletonFactories.remove(beanName);
            }
         }
      }
   }
   return singletonObject;
}

经过这个步骤,B已经注入了A,即B已经实例化完成,A依赖了B,则A也实例化完成。实例化完成后,就把二级三级缓存都清空,并放到一级缓存。

简单总结下:A实例化过程中,设置了第三级缓存,然后依赖注入B。B实例化过程中,也需要依赖注入A,那么会先从三级缓存中拿到A,完成依赖注入。既然B已经实例化完成,A也就相应的实例化完成。

实例化完成后的操作
DI依赖注入

AbstractAutowireCapableBeanFactory#doCreateBean

try {
   //ioc di,依赖注入的核心方法,该方法必须看,重要程度:5
   populateBean(beanName, mbd, instanceWrapper);
}
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   //...
   // 这里很有意思,写接口可以让所有类都不能依赖注入
   // 具体就是写一个InstantiationAwareBeanPostProcessor类型的类,实现postProcessAfterInstantiation方法,然后触发if里面的return操作
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               return;
            }
         }
      }
   }
   // ...
   PropertyDescriptor[] filteredPds = null;
   //重点看这个if代码块,重要程度 5
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            // 又是BeanPostProcessor的使用。依赖注入过程,@Autowired的支持。
            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               if (filteredPds == null) {
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
               }

               //老版本用这个完成依赖注入过程,@Autowired的支持
               pvsToUse = ibp.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);
   }

   //这个方法很鸡肋了,建议不看,是老版本用<property name="username" value="Jack"/>
   //标签做依赖注入的代码实现,复杂且无用
   if (pvs != null) {
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

AutowiredAnnotationBeanPostProcessor#postProcessProperties

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
   try {
      metadata.inject(bean, beanName, pvs); // 重点看inject方法
   }
   catch (BeanCreationException ex) {
      throw ex;
   }
   catch (Throwable ex) {
      throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
   }
   return pvs;
}

调用inject方法。主要遍历之前收集过的@Autowired标识的成员变量,然后进行注入操作。

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
   Collection<InjectedElement> checkedElements = this.checkedElements;
   // injectedElements表示收集到的@Autowired标识的成员变量,这个操作在前面完成了。
   Collection<InjectedElement> elementsToIterate =
         (checkedElements != null ? checkedElements : this.injectedElements);
   if (!elementsToIterate.isEmpty()) {
      for (InjectedElement element : elementsToIterate) {
         if (logger.isTraceEnabled()) {
            logger.trace("Processing injected element of bean '" + beanName + "': " + element);
         }
         element.inject(target, beanName, pvs); // 遍历每个成员变量,然后进行注入操作
      }
   }
}
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
      Field field = (Field) this.member;
      Object value;
      if (this.cached) {
         value = resolvedCachedArgument(beanName, this.cachedFieldValue);
      }
      else {
         DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
         desc.setContainingClass(bean.getClass());
         Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
         Assert.state(beanFactory != null, "No BeanFactory available");
         TypeConverter typeConverter = beanFactory.getTypeConverter();
         try {
            //这里会触发依赖注入属性的getBean操作,不表。
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
         }
         // ...
      }
      if (value != null) {
         ReflectionUtils.makeAccessible(field);
         field.set(bean, value);
      }
   }
}
bean实例化和di后执行的操作

AbstractAutowireCapableBeanFactory#doCreateBean

try {
   //bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5
   exposedObject = initializeBean(beanName, exposedObject, mbd);
}

initializeBean方法,主要就是对一些方法的调用。

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
   // ...
   else {
      //调用Aware方法
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      
      // 重点看几个:
      // ApplicationContextAwareProcessor,对某个Aware接口的调用,比如这么一些类型
      // EnvironmentAware EmbeddedValueResolverAware  ResourceLoaderAware ApplicationEventPublisherAware MessageSourceAware  ApplicationContextAware
      // ImportAwareBeanPostProcessor,对ImportAware的支持,对理解springboot很有帮助
      // InitDestroyAnnotationBeanPostProcessor,@PostConstruct方法的调用
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      // 会调用InitializingBean#afterPropertiesSet,init-method属性调用,非常重要,重要程度:5
      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()) {
      // 这个地方可能生出代理实例,是aop的入口,这里先别看,后面aop会单独拿出来讲
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}

调用aware方法,就是对BeanNameAware、BeanClassLoaderAware和BeanFactoryAware三种Aware的调用。

private void invokeAwareMethods(String beanName, Object bean) {
   if (bean instanceof Aware) {
      if (bean instanceof BeanNameAware) {
         ((BeanNameAware) bean).setBeanName(beanName);
      }
      if (bean instanceof BeanClassLoaderAware) {
         ClassLoader bcl = getBeanClassLoader();
         if (bcl != null) {
            ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
         }
      }
      if (bean instanceof BeanFactoryAware) {
         ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
      }
   }
}

applyBeanPostProcessorsBeforeInitialization,对各种各样类的调用,它们都实现了BeanPostProcessor

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   for (BeanPostProcessor processor : getBeanPostProcessors()) {
      Object current = processor.postProcessBeforeInitialization(result, beanName);
      if (current == null) {
         return result;
      }
      result = current;
   }
   return result;
}

invokeInitMethods,调用了InitializingBean#afterPropertiesSet、init-method方法

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
      throws Throwable {

   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      // ...
      else {
         //调用实现了InitializingBean接口的方法
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }

   if (mbd != null && bean.getClass() != NullBean.class) {
      String initMethodName = mbd.getInitMethodName();
      if (StringUtils.hasLength(initMethodName) &&
            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
         // 调用init-method配置的方法,就是通过反射去调用,不细看。
         invokeCustomInitMethod(beanName, bean, mbd);
      }
   }
}
销毁Bean

在Bean销毁后会调用销毁Bean的方法。

AbstractAutowireCapableBeanFactory#doCreateBean

try {
   //注册bean销毁时的类DisposableBeanAdapter
   registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
   throw new BeanCreationException(
         mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

注册销毁bean

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
   AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
   if (!mbd.isPrototype() && requiresDestruction(bean, mbd))  
      if (mbd.isSingleton()) {
         // 注册销毁bean
         registerDisposableBean(beanName,
               new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      }
      else {
         // A bean with a custom scope...
         Scope scope = this.scopes.get(mbd.getScope());
         if (scope == null) {
            throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
         }
         scope.registerDestructionCallback(beanName,
               new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      }
   }
}

是否需要注册销毁Bean:比如destroy-method、DisposableBean类型都可以注册销毁bean

protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
   return (bean.getClass() != NullBean.class &&
         (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
               DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}

把销毁bean存到集合中。

public void registerDisposableBean(String beanName, DisposableBean bean) {
   synchronized (this.disposableBeans) {
      this.disposableBeans.put(beanName, bean);
   }
}

我们只是简单的放置一个销毁bean,那么什么时候才会去调用这些销毁bean呢?

spring容器关闭时,就会调用销毁bean

AbstractApplicationContext#close

public void close() {
   synchronized (this.startupShutdownMonitor) {
      doClose();
      // ...
   }
}

进行bean的销毁,主要就是遍历之前的销毁bean集合,然后调用它们的destroy方法。

protected void doClose() {
   // Check whether an actual close attempt is necessary...
   if (this.active.get() && this.closed.compareAndSet(false, true)) {
      // ...

      // Destroy all cached singletons in the context's BeanFactory.
      // 进入这里进行bean的销毁
      destroyBeans();
     // ...
   }
}
protected void destroyBeans() {
   getBeanFactory().destroySingletons();
}
public void destroySingletons() {
   if (logger.isTraceEnabled()) {
      logger.trace("Destroying singletons in " + this);
   }
   synchronized (this.singletonObjects) {
      this.singletonsCurrentlyInDestruction = true;
   }

   String[] disposableBeanNames;
   synchronized (this.disposableBeans) { // 还记得这个disposableBeans吗?就是在Bean实例化后收集的销毁bean
      disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
   }
   for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
      // 遍历销毁bean
      destroySingleton(disposableBeanNames[i]);
   }

   this.containedBeanMap.clear();
   this.dependentBeanMap.clear();
   this.dependenciesForBeanMap.clear();

   clearSingletonCache();
}
public void destroySingleton(String beanName) {
   super.destroySingleton(beanName);
   removeManualSingletonName(beanName);
   clearByTypeCache();
}
public void destroySingleton(String beanName) {
   // Remove a registered singleton of the given name, if any.
   removeSingleton(beanName); // 从ioc移除销毁bean

   // Destroy the corresponding DisposableBean instance.
   DisposableBean disposableBean;
   synchronized (this.disposableBeans) {
      disposableBean = (DisposableBean) this.disposableBeans.remove(beanName); // 从销毁bean集合中移除销毁bean
   }
   destroyBean(beanName, disposableBean); // 继续跟踪
}
protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
   // ...

   // Actually destroy the bean now...
   if (bean != null) {
      try {
         bean.destroy(); // 调用DisposableBeanAdapter#destroy方法
      }
      catch (Throwable ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
         }
      }
   }
// ...
}
public void destroy() {
   //...
   if (this.destroyMethod != null) {
      // 调用自定义销毁方法
      invokeCustomDestroyMethod(this.destroyMethod);
   }
}

调用我们自定义的销毁方法,比如destroy-method、DisposableBean#destroy

private void invokeCustomDestroyMethod(final Method destroyMethod) {
   int paramCount = destroyMethod.getParameterCount();
   final Object[] args = new Object[paramCount];
   if (paramCount == 1) {
      args[0] = Boolean.TRUE;
   }
   // ...
      else {
         ReflectionUtils.makeAccessible(destroyMethod);
         destroyMethod.invoke(this.bean, args);  // 通过反射去调用销毁方法
      }
   }
  // ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值