首頁 > 軟體

Spring Bean生命週期之Bean的範例化詳解

2022-03-04 16:00:37

前言

上一節說到了BeanDefinition的合併過程,這節該說Bean的範例化過程了。根據AbstractAutowireCapableBeanFactory#createBean原始碼邏輯 可將範例化過程分為範例化前階段範例化過程範例化後階段

範例化前階段

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
		//省略無關程式碼
		try {
	       // 這裡就是我們分析的重點了 ⭐️
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			//⭐️ 注意這個邏輯:如果postProcessBeforeInstantiation方法返回非null 則將返回值作為建立的Bean。並中斷正常的建立流程
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			//省略異常資訊
		}
		try {
		    //真正建立Bean的邏輯 範例化Bean物件,為Bean屬性賦值等,這裡暫不展開
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			//省略紀錄檔輸出
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {//省略異常資訊
	}

resolveBeforeInstantiation這個方法在BeanPostProcessor淺析 這一節分析過了 這裡不再具體展開了。

如果InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 方法返回null,那麼將不會中斷正常Bean建立過程。
下面就來到的Bean範例化部分了。

範例化階段

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		//解析BeanClass,在BeanDefinition中類資訊是以字串形式展現,這裡解析到字串後 會將其載入為Class
		Class<?> beanClass = resolveBeanClass(mbd, beanName);
		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}
		//如果設定了 Supplier 回撥,則使用給定的回撥方法初始化策略,通過獲取Supplier#get得到範例化物件 
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}
 		//如果工廠方法不為空,則使用工廠方法初始化
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}
		
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
           //加鎖
			synchronized (mbd.constructorArgumentLock) {
            //條件成立 說明建構函式或FactoryMethod已經被解析並被快取,可直接利用建構函式解析
           //與後面的SimpleInstantiationStrategy#instantiate呼應
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
    //如果已經被解析過
		if (resolved) {
          //條件成立 使用建構函式注入
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
        //使用預設建構函式解析
				return instantiateBean(beanName, mbd);
			}
		}
    // 使用SmartInstantiationAwareBeanPostProcessor 找到候選的建構函式 用於注入
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    // AutowireMode==AUTOWIRE_CONSTRUCTOR 條件成立 說明使用基於建構函式的注入方式 (預設是AUTOWIRE_NO,需要動態檢測)
    // mbd.hasConstructorArgumentValues() 條件成立 說明建構函式中擁有引數
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      //基於建構函式自動注入
			return autowireConstructor(beanName, mbd, ctors, args);
		}
		// 如果mbd中設定了建構函式 則使用它進行注入
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}
		// 使用預設建構函式範例化
		return instantiateBean(beanName, mbd);
	}

上面將doCreateBean精簡一下,只暴露出我們比較關係的部分。一目瞭然,Bean的範例化過程就藏在createBeanInstance方法中。

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		//解析BeanClass,在BeanDefinition中類資訊是以字串形式展現,這裡解析到字串後 會將其載入為Class
		Class<?> beanClass = resolveBeanClass(mbd, beanName);
		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}
		//如果設定了 Supplier 回撥,則使用給定的回撥方法初始化策略,通過獲取Supplier#get得到範例化物件 
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}
 		//如果工廠方法不為空,則使用工廠方法初始化
		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}
		
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
           //加鎖
			synchronized (mbd.constructorArgumentLock) {
            //條件成立 說明建構函式或FactoryMethod已經被解析並被快取,可直接利用建構函式解析
           //與後面的SimpleInstantiationStrategy#instantiate呼應
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
    //如果已經被解析過
		if (resolved) {
          //條件成立 使用建構函式注入
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
        //使用預設建構函式解析
				return instantiateBean(beanName, mbd);
			}
		}
    // 使用SmartInstantiationAwareBeanPostProcessor 找到候選的建構函式 用於注入
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    // AutowireMode==AUTOWIRE_CONSTRUCTOR 條件成立 說明使用基於建構函式的注入方式 (預設是AUTOWIRE_NO,需要動態檢測)
    // mbd.hasConstructorArgumentValues() 條件成立 說明建構函式中擁有引數
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      //基於建構函式自動注入
			return autowireConstructor(beanName, mbd, ctors, args);
		}
		// 如果mbd中設定了建構函式 則使用它進行注入
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}
		// 使用預設建構函式範例化
		return instantiateBean(beanName, mbd);
	}

分析了上面的原始碼之後,我們試著總結一下上面程式碼主要完成的事情:

1、如果mbd設定了instanceSupplier回撥,則使用instanceSupplier去初始化BeanDefinition

2、如果mbd設定了工廠方法,則使用工廠方法區初始化BeanDefinition

3、範例化BeanDefinition

  • 如果mbd已經被解析過了,則根據快取 選擇使用有參建構函式注入還是預設建構函式注入
  • 如果mbd沒有被解析過,找到mbd中候選的建構函式(一個類可能有多個建構函式),再根據一些限定條件 選擇是基於有參建構函式初始化還是預設建構函式初始化

針對第1點,其實就是lambda8 supplier介面的使用,不再介紹。

針對第3點,其實就是通過反射機制 建立範例物件,最終呼叫了SimpleInstantiationStrategy#instantiate方法

針對第2點 舉例說明下 工廠方法靜態工廠生成Bean的兩種形式,再來展開說下instantiateUsingFactoryMethod原始碼。

設定Xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="peopleFactory" class="com.wojiushiwo.factorymethod.PeopleFactory"/>
    <!--實體方法-->
    <bean id="instanceMethod" factory-bean="peopleFactory" factory-method="createPeople"/>
		<!--靜態方法-->
    <bean id="staticFactoryMethod" class="com.wojiushiwo.factorymethod.People" factory-method="createPeople"/>
</beans>
//實體物件
@Data
public class People implements Serializable {
    private String name;
    private Integer age;
    public People() {
    }
    public static People createPeople() {
        People people = new People();
        people.setAge(18);
        people.setName("我就是我");
        return people;
    }
}
//People工廠類
public class PeopleFactory {
    public People createPeople() {
        return People.createPeople();
    }
}
public class FactoryMethodDemo {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("META-INF/spring.xml");
        context.refresh();
        People people = (People) context.getBean("staticFactoryMethod");
        System.out.println(people);
		People people = (People) context.getBean("instanceMethod");
        System.out.println(people);		
        context.close();
    }
}
public BeanWrapper instantiateUsingFactoryMethod(
			String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
		BeanWrapperImpl bw = new BeanWrapperImpl();
		this.beanFactory.initBeanWrapper(bw);
		Object factoryBean;
		Class<?> factoryClass;
		boolean isStatic;
		//獲取FactoryBeanName,實體方法與靜態工廠方法的區別就在於有沒有FactoryBeanName
		String factoryBeanName = mbd.getFactoryBeanName();
		if (factoryBeanName != null) {
      //如果存在FactoryBeanName,則說明是實體方法
			if (factoryBeanName.equals(beanName)) {
				throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
						"factory-bean reference points back to the same bean definition");
			}
      //獲取當前factoryBeanName名稱的Bean
			factoryBean = this.beanFactory.getBean(factoryBeanName);
			if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
				throw new ImplicitlyAppearedSingletonException();
			}
      //獲取工廠類Class
			factoryClass = factoryBean.getClass();
      //標記為非靜態
			isStatic = false;
		}
		else {
			// 走到這裡,說明是靜態工廠方法
			if (!mbd.hasBeanClass()) {
				throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
						"bean definition declares neither a bean class nor a factory-bean reference");
			}
      //factoryBean設定為null
			factoryBean = null;
      //獲取工廠類Class,這裡使用BeanDefinition作為其工廠類
			factoryClass = mbd.getBeanClass();
      //標記為非靜態
			isStatic = true;
		}
		Method factoryMethodToUse = null;
		ArgumentsHolder argsHolderToUse = null;
		Object[] argsToUse = null;
		//explicitArgs 這個是getBean方法傳遞過來的,一般為null
		if (explicitArgs != null) {
			argsToUse = explicitArgs;
		}
		else {
			Object[] argsToResolve = null;
      //加鎖
			synchronized (mbd.constructorArgumentLock) {
        //獲取被解析的工廠方法
				factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
        //條件成立 說明工廠方法已經被解析過了,並存到了mbd中快取起來了
				if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
					// Found a cached factory method...
					argsToUse = mbd.resolvedConstructorArguments;
					if (argsToUse == null) {
						argsToResolve = mbd.preparedConstructorArguments;
					}
				}
			}
			if (argsToResolve != null) {
				argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);
			}
		}
		if (factoryMethodToUse == null || argsToUse == null) {
      //獲取工廠類
			factoryClass = ClassUtils.getUserClass(factoryClass);
			//獲取類中的方法
			Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
			List<Method> candidateList = new ArrayList<>();
			for (Method candidate : rawCandidates) {
        //如果方法修飾符包含static,並且方法名稱是設定的FactoryMethod,則新增到候選集合中
				if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
					candidateList.add(candidate);
				}
			}
		  //如果候選集合有1個元素 並且BeanDefinition中未設定構造引數 (explicitArgs一般都為null )
			if (candidateList.size() == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
        //獲取方法
				Method uniqueCandidate = candidateList.get(0);
        //如果方法引數為空
				if (uniqueCandidate.getParameterCount() == 0) {
					mbd.factoryMethodToIntrospect = uniqueCandidate;
					synchronized (mbd.constructorArgumentLock) {
            //將下面這些全快取到mbd中,下次直接用(與createBeanInstance方法呼應上了)
						mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
						mbd.constructorArgumentsResolved = true;
						mbd.resolvedConstructorArguments = EMPTY_ARGS;
					}
          //範例化bd,設定到BeanWrapper中
					bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, uniqueCandidate, EMPTY_ARGS));
					return bw;
				}
			}
			//程式走到這裡 大概率是BeanDefinition中設定了構造引數
			Method[] candidates = candidateList.toArray(new Method[0]);
      //按照修飾符及方法引數 進行排序
			AutowireUtils.sortFactoryMethods(candidates);
			ConstructorArgumentValues resolvedValues = null;
      //是否建構函式注入
			boolean autowiring = (mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
			int minTypeDiffWeight = Integer.MAX_VALUE;
			Set<Method> ambiguousFactoryMethods = null;
      //最小引數數量 預設是0
			int minNrOfArgs;
			if (explicitArgs != null) {
				minNrOfArgs = explicitArgs.length;
			}
			else {
        //走到這裡 說明explicitArgs未被設定引數
        //如果bd設定了構造引數,則從bd中解析引數
				if (mbd.hasConstructorArgumentValues()) {
					ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
					resolvedValues = new ConstructorArgumentValues();
          //得到解析的最小引數數量
					minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
				}
				else {
					minNrOfArgs = 0;
				}
			}
			LinkedList<UnsatisfiedDependencyException> causes = null;
			//下面主要是推斷引數、FactoryMethod,程式碼比較長 就先不分析了
			for (Method candidate : candidates) {
				Class<?>[] paramTypes = candidate.getParameterTypes();
				if (paramTypes.length >= minNrOfArgs) {
					ArgumentsHolder argsHolder;
					if (explicitArgs != null) {
						// Explicit arguments given -> arguments length must match exactly.
						if (paramTypes.length != explicitArgs.length) {
							continue;
						}
						argsHolder = new ArgumentsHolder(explicitArgs);
					}
					else {
						// Resolved constructor arguments: type conversion and/or autowiring necessary.
						try {
							String[] paramNames = null;
							ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
							if (pnd != null) {
								paramNames = pnd.getParameterNames(candidate);
							}
							argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw,
									paramTypes, paramNames, candidate, autowiring, candidates.length == 1);
						}
						catch (UnsatisfiedDependencyException ex) {
							if (logger.isTraceEnabled()) {
								logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName + "': " + ex);
							}
							// Swallow and try next overloaded factory method.
							if (causes == null) {
								causes = new LinkedList<>();
							}
							causes.add(ex);
							continue;
						}
					}
					int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
							argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
					// Choose this factory method if it represents the closest match.
					if (typeDiffWeight < minTypeDiffWeight) {
						factoryMethodToUse = candidate;
						argsHolderToUse = argsHolder;
						argsToUse = argsHolder.arguments;
						minTypeDiffWeight = typeDiffWeight;
						ambiguousFactoryMethods = null;
					}
					// Find out about ambiguity: In case of the same type difference weight
					// for methods with the same number of parameters, collect such candidates
					// and eventually raise an ambiguity exception.
					// However, only perform that check in non-lenient constructor resolution mode,
					// and explicitly ignore overridden methods (with the same parameter signature).
					else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight &&
							!mbd.isLenientConstructorResolution() &&
							paramTypes.length == factoryMethodToUse.getParameterCount() &&
							!Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
						if (ambiguousFactoryMethods == null) {
							ambiguousFactoryMethods = new LinkedHashSet<>();
							ambiguousFactoryMethods.add(factoryMethodToUse);
						}
						ambiguousFactoryMethods.add(candidate);
					}
				}
			}
			if (factoryMethodToUse == null) {
				if (causes != null) {
					UnsatisfiedDependencyException ex = causes.removeLast();
					for (Exception cause : causes) {
						this.beanFactory.onSuppressedException(cause);
					}
					throw ex;
				}
				List<String> argTypes = new ArrayList<>(minNrOfArgs);
				if (explicitArgs != null) {
					for (Object arg : explicitArgs) {
						argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
					}
				}
				else if (resolvedValues != null) {
					Set<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
					valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
					valueHolders.addAll(resolvedValues.getGenericArgumentValues());
					for (ValueHolder value : valueHolders) {
						String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) :
								(value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
						argTypes.add(argType);
					}
				}
				String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
				//丟擲異常
			}
			else if (void.class == factoryMethodToUse.getReturnType()) {
				//丟擲異常
			}
			else if (ambiguousFactoryMethods != null) {
				//丟擲異常
			}
			if (explicitArgs == null && argsHolderToUse != null) {
				mbd.factoryMethodToIntrospect = factoryMethodToUse;
				argsHolderToUse.storeCache(mbd, factoryMethodToUse);
			}
		}
		Assert.state(argsToUse != null, "Unresolved factory method arguments");
    //範例化bd 設定到BeanWrapper中
		bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, factoryMethodToUse, argsToUse));
		return bw;
	}

至此經過createBeanInstance方法 就為我們建立了一個範例物件,但是現在這個物件屬性還未被賦值。

範例化後階段

範例物件建立之後,就來到了物件屬性賦值過程了,我們大致看一下populateBean方法,觀察下InstantiationAwareBeanPostProcessor對屬性賦值過程的影響

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		//省略無關程式碼
		boolean continueWithPropertyPopulation = true;
		//條件一 synthetic預設值是false 一般都會成立
		//條件二 成立的話 說明存在InstantiationAwareBeanPostProcessor
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//在BeanPostProcessor淺析中分析到此方法時說過,若Bean範例化後回撥不返回true 則對屬性賦值過程產生影響。以下程式碼就是說明
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}
		//ibp.postProcessAfterInstantiation=false時 屬性賦值過程終止
		if (!continueWithPropertyPopulation) {
			return;
		}

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!   


IT145.com E-mail:sddin#qq.com