spring源码IOC初始化过程-第11个方法源码分析-finishBeanFactoryInitialization(beanFactory);

前言

这篇文章分析的是spring(环境,容器,上下文)初始化过程种调用的最重要的方法之一
finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)
这个方法中让所有注册在springIOC容器中的对象经历了bean生命周期最终成为一个bean存放在单例池中,过程中解决了Bean循环依赖,依赖的Bean经过AOP如何处理等问题

由于spring容器初始化过程十分复杂,防止迷茫,请有选择的查看!
其他方法的源码请查看我的其他文章

11、finishBeanFactoryInitialization(beanFactory);

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			
       // 1.为容器刷新做一些准备工作
			prepareRefresh();

			// 2.告诉子类刷新内部bean工厂
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 3.为beanFactory做一些预录准备工作
			prepareBeanFactory(beanFactory);
      
// ===至此,BeanFactory已经创建了,里面该设置的属性和准备工作都完成了

			try {
				// 4.允许子类在beanFactory创建 通过配置类注册的组件创建前进行后置处理。
        //这个方法在当前版本的spring是没用任何代码的//可能spring期待在后面的版本中去扩展吧
				postProcessBeanFactory(beanFactory);

// ===下面正式开始按按接口优先级分类创建组件

*********// 5.创建BeanFactoryPostProcessor接口和子接口BeanDefinitionRegistryPostProcessor类型组件并调用后置方法
  			// 完成业务类(我们自定义的Bean)扫描放入一个map中
				invokeBeanFactoryPostProcessors(beanFactory);

				// 6.创建BeanPostProcessor接口类型组件在后期普通Bean组件被初始化前后调用
				registerBeanPostProcessors(beanFactory);

				// 7.国际化
				initMessageSource();

				// 8.为此上下文初始化事件多播器。
				initApplicationEventMulticaster();

				// 9.Initialize other special beans in specific context subclasses.
				onRefresh();

				// 10.检查侦听器bean并注册它们。
				registerListeners();

**当前文章分析这个方法**// 11.实例化所有剩余的(非延迟-init)单例。
				finishBeanFactoryInitialization(beanFactory);

				// 12.最后一步:发布相应的事件。
				finishRefresh();
			}

refresh()方法中第11个方法: 初始化所有剩下的单实例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(new StringValueResolver() {
      @Override
      public String resolveStringValue(String strVal) {
        return 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);

  // Allow for caching all bean definition metadata, not expecting further changes.
  beanFactory.freezeConfiguration();

 ************// 11.0实例化所有剩余的非延迟单例的Bean	↓
  beanFactory.preInstantiateSingletons();
}

public void preInstantiateSingletons() throws BeansException {
  
	// 11、1获取注册在容器中的所有BeanDefinition信息,依次进行初始化和创建对象
  //说明:所有的BeanDefiton存放在ConCurrentHasmMap类型的beanDefitionMap中
  //		另外还将所有的BeanDefiton的k存了一份在ArrayList类型的beanDefitionNames中
  List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
	
  // 触发所有非懒加载单例bean的初始化...
  
  // 11.2、遍历判断Bean的定义信息;(根据beanDefitionNames集合中的名字取出beanDefitionMap的bd信息)
  for (String beanName : beanNames) {
    RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    // 11.3、Bean不是抽象的,是单实例的,是懒加载;
    if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      // 11.3.1、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
      if (isFactoryBean(beanName)) {
        final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
        boolean isEagerInit;
        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
          isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            @Override
            public Boolean run() {
              return ((SmartFactoryBean<?>) factory).isEagerInit();
            }
          }, getAccessControlContext());
        }
        else {
          isEagerInit = (factory instanceof SmartFactoryBean &&
                         ((SmartFactoryBean<?>) factory).isEagerInit());
        }
        if (isEagerInit) {
          getBean(beanName);
        }
      }
      //11.3.2、不是工厂Bean。就利用getBean(beanName);创建这个bean 
      else {
//*******核心代码getBean(beanName)******************************↓
        getBean(beanName);
      }
    }
  }

  // Trigger post-initialization callback for all applicable beans...
  for (String beanName : beanNames) {
    Object singletonInstance = getSingleton(beanName);
    if (singletonInstance instanceof SmartInitializingSingleton) {
      final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
          @Override
          public Object run() {
            smartSingleton.afterSingletonsInstantiated();
            return null;
          }
        }, getAccessControlContext());
      }
      else {
        smartSingleton.afterSingletonsInstantiated();
      }
    }
  }
}
public Object getBean(String name) throws BeansException {
  return doGetBean(name, null, null, false);
}
---------------------------------------------------------------------------
protected <T> T doGetBean(
	final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)throws BeansException {

		final String beanName = transformedBeanName(name);
		Object bean;

// 11.3.2.1、先尝试从单例池中获取这个Bean。(所有创建过的单实例Bean都会存入在singletonObjects单例池中)
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
			
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}
		
      //11.3.2.2、缓存中获取不到,开始Bean的创建对象流程;
		else {
			
			
			// 11.3.2.3、标记当前bean已经被创建,防止多线程影响
			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}
			//5、获取Bean的定义信息;
			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				//6、获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;
				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);
//************************解决当前bean依赖其他bean的问题*******************************⬇
						getBean(dep);
					}
				}

				// 7、启动单实例Bean的创建流程;
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
//**************************⬇
								return createBean(beanName, mbd, args);
							}
--------------------------------------------------------------------------
  protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
		RootBeanDefinition mbdToUse = mbd;
  
		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
//*****************************(解决当前bean依赖的bean是经过AOP的)
//**************给BeanPostProcessors一个 返回代理对象而不是目标 bean实例的机会。
			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);
		}

		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		
		return beanInstance;
	}
  
--------------------------------------------------------------------------
             
							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();
					final 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, new ObjectFactory<Object>() {
							@Override
							public Object getObject() throws BeansException {
								beforePrototypeCreation(beanName);
								try {
									return createBean(beanName, mbd, args);
								}
								finally {
									afterPrototypeCreation(beanName);
								}
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

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

总结

1、beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
   1)、根据beanNameS.forEach(1.获取beanDefinitionMapbeanDefinition,2.依次进行初始化和创建对象)
   			(所有Bean是指不管是我们自己写的,还是容器默认导入的,不管是前面步骤已经创建了的还是没创建的)
   2)、获取Bean的定义信息;RootBeanDefinition
   3)、Bean不是抽象的,是单实例的,是懒加载;
      1)、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
      2)、不是工厂Bean。利用getBean(beanName);创建对象
         0、getBean(beanName)→ singletonObjects.getBean(beanName);
         1、doGetBean(name, null, null, false);
         2、先获取单例池中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会存入单例池)
         从private final Map singletonObjects=new ConcurrentHashMap(256);获取的
         3、单例池中获取不到,开始Bean的创建流程;
         4、标记当前bean已经被创建,防止多线程重复创建这个bean,(标记其实就是将当前beanName存入一个线程安全的List中)
         5、获取Bean的定义信息;
*********6、【获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;】
         7、启动单实例Bean的创建流程;
            1)、createBean(beanName, mbd, args);
*************解决依赖的bean是经过Aop的
            2)、Object bean=resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor先拦截返回代理象;
               
               【InstantiationAwareBeanPostProcessor】:提前执行;
               先触发:postProcessBeforeInstantiation();
               如果有返回值:触发postProcessAfterInitialization();
            3)、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用4)
            getBean()
            
*******进入狭义的bean生命周期:专注创建Bean(bean依赖,aop在前面已经判断了,此刻真正安心去创建bean)*************
----------1.Bean实例化-----2.填充属性(依赖注入,Aware)—--3.(初始前)**初始化**(初始后)--—4.销毁------------
            4)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);
                1)、【创建Bean实例】;createBeanInstance(beanName, mbd, args);
                  利用工厂方法或者反射Class.forName()创建出Bean实例;
                2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                  调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, bName);
                3)、【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
                  赋值之前:
                  1)、拿到InstantiationAwareBeanPostProcessor后置处理器;
                     postProcessAfterInstantiation();
                  2)、拿到InstantiationAwareBeanPostProcessor后置处理器;
                     postProcessPropertyValues();
                 
                  3)、应用Bean属性的值;为属性利用setter方法等进行赋值;
                     applyPropertyValues(beanName, mbd, bw, pvs);
                4)、【Bean初始化】initializeBean(beanName, exposedObject, mbd);
                  1)、【执行Aware接口方法】invokeAwareMethods(beanName, bean);执行xxxAware接口的方法
                     BeanNameAware\BeanClassLoaderAware\BeanFactoryAware
                  2)、【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, bName);
                     BeanPostProcessor.postProcessBeforeInitialization();
                  3)、【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
                     1)、判断当前Bean是否是InitializingBean接口的实现;执行接口规定的初始化方法;
                     2)、是否自定义初始化方法;
                  4)、【执行后置处理器初始化之后】applyBeanPostProcessorsAfterInitialization
                     BeanPostProcessor.postProcessAfterInitialization();
                5)、注册Bean的销毁方法;
            5)、将创建的Bean添加单例池singletonObjects中;
   所有Bean都利用getBean创建完成以后;
      检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();

你可能感兴趣的:(spring,ioc,java,源码,aop)