spring啟動流程 (5) Autowired原理

来源:https://www.cnblogs.com/xugf/archive/2023/07/17/17559762.html
-Advertisement-
Play Games

# 構造方法參數Autowire - BeanClass可以在構造方法上標註@Autowired註解,Spring在創建Bean實例時將自動為其註入依賴參數 - Spring會優先使用標註@Autowired註解的構造方法 - 當一個構造方法標註了@Autowired註解且required=true ...


構造方法參數Autowire

  • BeanClass可以在構造方法上標註@Autowired註解,Spring在創建Bean實例時將自動為其註入依賴參數
  • Spring會優先使用標註@Autowired註解的構造方法
  • 當一個構造方法標註了@Autowired註解且required=true時,其餘構造方法不允許再標註@Autowired註解
  • 當多個構造方法標註了@Autowired註解且required=false時,它們會成為候選者,Spring將選擇具有最多依賴項的構造方法
  • 如果沒有候選者可以滿足,Spring將使用預設的無參構造方法(如果存在)
  • 如果Class有多個含參構造方法,且都沒有標註@Autowired註解,此時在創建Bean時會拋錯

Spring創建Bean實例

創建Bean實例在AbstractAutowireCapableBeanFactory類的createBeanInstance方法:

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
	// Make sure bean class is actually resolved at this point.
	Class<?> beanClass = resolveBeanClass(mbd, beanName);

	// public和access判斷,略

	Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
	if (instanceSupplier != null) {
		return obtainFromSupplier(instanceSupplier, beanName);
	}

	// 使用工廠創建Bean實例,@Bean註解標註的方法會使用這種方式創建Bean實例
	// 後續有章節進行分析
	if (mbd.getFactoryMethodName() != null) {
		return instantiateUsingFactoryMethod(beanName, mbd, args);
	}

	// Shortcut when re-creating the same bean...
	boolean resolved = false;
	boolean autowireNecessary = false;
	if (args == null) {
		synchronized (mbd.constructorArgumentLock) {
			if (mbd.resolvedConstructorOrFactoryMethod != null) {
				resolved = true;
				autowireNecessary = mbd.constructorArgumentsResolved;
			}
		}
	}
	if (resolved) {
		if (autowireNecessary) {
			return autowireConstructor(beanName, mbd, null, null);
		} else {
			return instantiateBean(beanName, mbd);
		}
	}

	// 獲取候選的構造方法
	Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
	if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
			mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
		// 使用構造方法創建Bean實例
		return autowireConstructor(beanName, mbd, ctors, args);
	}

	// 此處通過RootBeanDefinition獲取候選的構造方法然後創建Bean實例,和上面基本一致
	ctors = mbd.getPreferredConstructors();
	if (ctors != null) {
		return autowireConstructor(beanName, mbd, ctors, null);
	}

	// 使用預設構造方法創建Bean實例
	return instantiateBean(beanName, mbd);
}

獲取候選的構造方法集

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

	// Let's check for lookup methods here...
	// 略

	// 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 {
					// 使用java反射獲取聲明瞭的所有構造方法
					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);
				// 標註@Autowired註解且required=true的構造方法
				Constructor<?> requiredConstructor = null;
				// 預設的無參構造方法
				Constructor<?> defaultConstructor = null;
				// 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) {
						// 如果之前已經找到了requiredConstructor則拋錯
						if (requiredConstructor != null) {
							throw new BeanCreationException(beanName,
									"Invalid autowire-marked constructor: " + candidate +
									". Found constructor with 'required' Autowired annotation already: " +
									requiredConstructor);
						}
						boolean required = determineRequiredStatus(ann);
						// 構造方法標註@Autowired註解且required=true
						if (required) {
							if (!candidates.isEmpty()) {
								throw new BeanCreationException(beanName,
										"Invalid autowire-marked constructors: " + candidates +
										". Found constructor with 'required' Autowired annotation: " +
										candidate);
							}
							requiredConstructor = candidate;
						}
						// 將構造方法添加到candidates集
						candidates.add(candidate);
					} else if (candidate.getParameterCount() == 0) {
						defaultConstructor = candidate;
					}
				}
				if (!candidates.isEmpty()) {
					// 把預設無參構造方法添加到candidates集
					if (requiredConstructor == null) {
						if (defaultConstructor != null) {
							candidates.add(defaultConstructor);
						}
					}
					candidateConstructors = candidates.toArray(new Constructor<?>[0]);
				} else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
					// 當candidates為空時,即所有構造方法都沒有標註@Autowired註解
					// 且只有一個構造方法時,預設使用這個構造方法
					candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
				} else {
					candidateConstructors = new Constructor<?>[0];
				}
				// 維護緩存
				this.candidateConstructorsCache.put(beanClass, candidateConstructors);
			}
		}
	}
	return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

使用構造方法創建Bean實例

autowireConstructor(beanName, mbd, ctors, args);

autowireConstructor方法:

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

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

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

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

	Constructor<?> constructorToUse = null;
	ArgumentsHolder argsHolderToUse = null;
	Object[] argsToUse = null;

	// explicitArgs == null
	if (explicitArgs != null) {
		argsToUse = explicitArgs;
	} else {
		Object[] argsToResolve = null;
		// 獲取mbd中緩存的構造方法和參數並用其創建對象,此處不詳細分析
		synchronized (mbd.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
			if (constructorToUse != null && mbd.constructorArgumentsResolved) {
				argsToUse = mbd.resolvedConstructorArguments;
				if (argsToUse == null) {
					argsToResolve = mbd.preparedConstructorArguments;
				}
			}
		}
		if (argsToResolve != null) {
			argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
		}
	}

	// 這裡從候選構造方法集選擇一個最佳構造方法
	if (constructorToUse == null || argsToUse == null) {
		Constructor<?>[] candidates = chosenCtors;
		if (candidates == null) {
			// 使用反射獲取聲明的所有構造方法
		}

		// 只有一個無參的預設構造方法
		// 1. 將其放入mbd緩存起來
		// 2. 使用這個構造方法創建Bean實例並返回
		if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
			Constructor<?> uniqueCandidate = candidates[0];
			if (uniqueCandidate.getParameterCount() == 0) {
				synchronized (mbd.constructorArgumentLock) {
					mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
					mbd.constructorArgumentsResolved = true;
					mbd.resolvedConstructorArguments = EMPTY_ARGS;
				}
				bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
				return bw;
			}
		}

		// Need to resolve the constructor.
		boolean autowiring = (chosenCtors != null ||
				mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
		ConstructorArgumentValues resolvedValues = null;

		int minNrOfArgs;
		if (explicitArgs != null) {
			minNrOfArgs = explicitArgs.length;
		} else {
			ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
			resolvedValues = new ConstructorArgumentValues();
			minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
		}

		// 排序,參數多的排在前面
		AutowireUtils.sortConstructors(candidates);
		int minTypeDiffWeight = Integer.MAX_VALUE;
		Set<Constructor<?>> ambiguousConstructors = null;
		LinkedList<UnsatisfiedDependencyException> causes = null;

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

			if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
				// 已經找到了合適的構造方法,可以跳出去了
				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);
						}
					}
					// 解析構造方法需要的參數
					argsHolder = createArgumentArray(
                        	beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
							getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
				} catch (UnsatisfiedDependencyException ex) {
					// Swallow and try next constructor.
					if (causes == null) {
						causes = new LinkedList<>();
					}
					causes.add(ex);
					continue;
				}
			} else {
				// Explicit arguments given -> arguments length must match exactly.
				if (parameterCount != explicitArgs.length) {
					continue;
				}
				argsHolder = new ArgumentsHolder(explicitArgs);
			}

			int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
									argsHolder.getTypeDifferenceWeight(paramTypes) : 
									argsHolder.getAssignabilityWeight(paramTypes));
			// Choose this constructor if it represents the closest match.
			if (typeDiffWeight < minTypeDiffWeight) {
				constructorToUse = candidate;
				argsHolderToUse = argsHolder;
				argsToUse = argsHolder.arguments;
				minTypeDiffWeight = typeDiffWeight;
				ambiguousConstructors = null;
			} else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
				if (ambiguousConstructors == null) {
					ambiguousConstructors = new LinkedHashSet<>();
					ambiguousConstructors.add(constructorToUse);
				}
				ambiguousConstructors.add(candidate);
			}
		}

		if (constructorToUse == null) {
			if (causes != null) {
				UnsatisfiedDependencyException ex = causes.removeLast();
				for (Exception cause : causes) {
					this.beanFactory.onSuppressedException(cause);
				}
				throw ex;
			}
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Could not resolve matching constructor");
		} else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Ambiguous constructor matches found in bean");
		}

		if (explicitArgs == null && argsHolderToUse != null) {
			argsHolderToUse.storeCache(mbd, constructorToUse);
		}
	}

	// 使用選擇到的構造方法創建Bean實例
	bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
	return bw;
}

欄位和setter方法參數Autowire

創建Bean流程

在Bean實例化流程分析時,我們瞭解到在AbstractAutowireCapableBeanFactory類doCreateBean方法會創建Bean實例併進行初始化和依賴註入:

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) {
		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 {
				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) {
		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
	}

	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
		// 依賴註入
		populateBean(beanName, mbd, instanceWrapper);
		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);
		}
	}

	// 略

	return exposedObject;
}

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
	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;
		}
	}

	// 調用InstantiationAwareBeanPostProcessor處理器postProcessAfterInstantiation方法
	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}
	}

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

	// 自動註入setter
	// AUTOWIRE_BY_NAME和AUTOWIRE_BY_TYPE兩種模式會進入分支進行處理
	// 預設AUTOWIRE_NO模式
	// 此處僅處理有setter方法的屬性
	int resolvedAutowireMode = mbd.getResolvedAutowireMode();
	if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
		// 使用屬性名稱註入
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// 使用屬性類型註入
		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 (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				// 此處調用InstantiationAwareBeanPostProcessor處理器postProcessProperties方法
				// AutowiredAnnotationBeanPostProcessor實現類中有依賴註入的邏輯
				PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					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);
	}

	if (pvs != null) {
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

AutowiredAnnotationBeanPostProcessor處理器

此處理器為標註了@Autowired的欄位和方法進行自動註入。

也會處理@Value註解,這個暫時不做分析。

postProcessProperties方法

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
	// 獲取到標註了@Autowired註解的欄位和方法
	InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
	try {
		// 為欄位和方法做依賴註入
		metadata.inject(bean, beanName, pvs);
	} catch (BeanCreationException ex) {
		throw ex;
	} catch (Throwable ex) {
		throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
	}
	return pvs;
}

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) {
	// Fall back to class name as cache key, for backwards compatibility with custom callers.
	String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
	// Quick check on the concurrent map first, with minimal locking.
	InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
	if (InjectionMetadata.needsRefresh(metadata, clazz)) {
		synchronized (this.injectionMetadataCache) {
			metadata = this.injectionMetadataCache.get(cacheKey);
			if (InjectionMetadata.needsRefresh(metadata, clazz)) {
				if (metadata != null) {
					metadata.clear(pvs);
				}
				// 獲取到標註了@Autowired註解的欄位和方法
				metadata = buildAutowiringMetadata(clazz);
				this.injectionMetadataCache.put(cacheKey, metadata);
			}
		}
	}
	return metadata;
}

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
	if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
		return InjectionMetadata.EMPTY;
	}

	List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
	Class<?> targetClass = clazz;

	do {
		final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

		ReflectionUtils.doWithLocalFields(targetClass, field -> {\
			// 獲取欄位上標註的@Autowired和@Value註解
			MergedAnnotation<?> ann = findAutowiredAnnotation(field);
			if (ann != null) {
				// 靜態欄位不處理
				if (Modifier.isStatic(field.getModifiers())) {
					return;
				}
				boolean required = determineRequiredStatus(ann);
				// 添加到InjectedElement集
				currElements.add(new AutowiredFieldElement(field, required));
			}
		});

		ReflectionUtils.doWithLocalMethods(targetClass, method -> {
			Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
			if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
				return;
			}
			MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
			if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
				// 靜態方法不處理
				if (Modifier.isStatic(method.getModifiers())) {
					return;
				}
				boolean required = determineRequiredStatus(ann);
				PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
				currElements.add(new AutowiredMethodElement(method, required, pd));
			}
		});

		elements.addAll(0, currElements);
		targetClass = targetClass.getSuperclass();
	} while (targetClass != null && targetClass != Object.class);

	return InjectionMetadata.forElements(elements, clazz);
}

依賴註入:

metadata.inject(bean, beanName, pvs);

inject的實現在InjectionMetadata類:

public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
	Collection<InjectedElement> checkedElements = this.checkedElements;
	Collection<InjectedElement> elementsToIterate =
			(checkedElements != null ? checkedElements : this.injectedElements);
	if (!elementsToIterate.isEmpty()) {
		for (InjectedElement element : elementsToIterate) {
			// 調用InjectedElement的inject方法為欄位或方法註入依賴
			// 從之前的方法可以知道,element是AutowiredFieldElement或AutowiredMethodElement對象
			element.inject(target, beanName, pvs);
		}
	}
}

AutowiredFieldElement類

AutowiredFieldElement的inject方法:

protected void inject(Object bean, String beanName, 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);
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		try {
			// 使用beanFactory從容器裡面獲取依賴的Bean
			value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
		} catch (BeansException ex) {
			throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
		}
		synchronized (this) {
			if (!this.cached) {
				Object cachedFieldValue = null;
				if (value != null || this.required) {
					cachedFieldValue = desc;
					registerDependentBeans(beanName, autowiredBeanNames);
					if (autowiredBeanNames.size() == 1) {
						String autowiredBeanName = autowiredBeanNames.iterator().next();
						if (beanFactory.containsBean(autowiredBeanName) &&
								beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
							cachedFieldValue = new ShortcutDependencyDescriptor(
									desc, autowiredBeanName, field.getType());
						}
					}
				}
				this.cachedFieldValue = cachedFieldValue;
				this.cached = true;
			}
		}
	}
	if (value != null) {
		// 為欄位設置值
		ReflectionUtils.makeAccessible(field);
		field.set(bean, value);
	}
}

從容器獲取依賴的Bean實例:

public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,
		Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
	if (Optional.class == descriptor.getDependencyType()) {
		return createOptionalDependency(descriptor, requestingBeanName);
	} else if (ObjectFactory.class == descriptor.getDependencyType() ||
			ObjectProvider.class == descriptor.getDependencyType()) {
		return new DependencyObjectProvider(descriptor, requestingBeanName);
	} else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
	} else {
		// 此處處理Lazy註解,使用代理
		// 返回一個代理對象,在攔截方法時從容器裡面獲取真實的Bean實例再調用目標方法
		// 只是創建代理,不做展開分析
		Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
				descriptor, requestingBeanName);
		if (result == null) {
			// 從容器裡面獲取依賴的Bean實例
			result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
		}
		return result;
	}
}

public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
		Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

	InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
	try {
		Object shortcut = descriptor.resolveShortcut(this);
		if (shortcut != null) {
			return shortcut;
		}

		Class<?> type = descriptor.getDependencyType();

		// 為@Value註解註入值
		Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
		if (value != null) {
			if (value instanceof String) {
				String strVal = resolveEmbeddedValue((String) value);
				BeanDefinition bd = (beanName != null && containsBean(beanName) ?
						getMergedBeanDefinition(beanName) : null);
				value = evaluateBeanDefinitionString(strVal, bd);
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			try {
				return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
			} catch (UnsupportedOperationException ex) {
				return (descriptor.getField() != null ?
						converter.convertIfNecessary(value, type, descriptor.getField()) :
						converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
			}
		}

		// 數組、集合、Map
		Object multipleBeans =
            resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
		if (multipleBeans != null) {
			return multipleBeans;
		}

		// 根據依賴的數據類型從容器裡面查找符合的Bean
		// BeanName -> BeanClass的映射
		Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
		if (matchingBeans.isEmpty()) {
			if (isRequired(descriptor)) {
				// 沒有找到拋出NoSuchBeanDefinitionException異常
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			return null;
		}

		String autowiredBeanName;
		Object instanceCandidate;

		if (matchingBeans.size() > 1) {
			// 當找到多個類型符合的Bean需要選擇一個最合適的
			// 1. 找標註了@Primary註解的Bean
			// 2. 找javax.annotation.Priority配置最高的Bean
			// 3. 找beanName與欄位名相符或bean別名與欄位名相符的Bean
			autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
			if (autowiredBeanName == null) {
				if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
					return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
				} else {
					return null;
				}
			}
			instanceCandidate = matchingBeans.get(autowiredBeanName);
		} else {
			// We have exactly one match.
			Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
			autowiredBeanName = entry.getKey();
			instanceCandidate = entry.getValue();
		}

		if (autowiredBeanNames != null) {
			autowiredBeanNames.add(autowiredBeanName);
		}
		if (instanceCandidate instanceof Class) {
			// 使用beanName到容器裡面找Bean實例
			instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
		}
		Object result = instanceCandidate;
		if (result instanceof NullBean) {
			if (isRequired(descriptor)) {
				// 沒有找到拋出NoSuchBeanDefinitionException異常
				raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
			}
			result = null;
		}
		if (!ClassUtils.isAssignableValue(type, result)) {
			throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
		}
		return result;
	} finally {
		ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
	}
}

AutowiredMethodElement類

protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
	// pvs包含就不處理
	if (checkPropertySkipping(pvs)) {
		return;
	}
	Method method = (Method) this.member;
	Object[] arguments;
	if (this.cached) {
		arguments = resolveCachedArguments(beanName);
	} else {
		// 從容器查找依賴的Bean
		int argumentCount = method.getParameterCount();
		arguments = new Object[argumentCount];
		DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount];
		Set<String> autowiredBeans = new LinkedHashSet<>(argumentCount);
		TypeConverter typeConverter = beanFactory.getTypeConverter();
		for (int i = 0; i < arguments.length; i++) {
			MethodParameter methodParam = new MethodParameter(method, i);
			DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
			currDesc.setContainingClass(bean.getClass());
			descriptors[i] = currDesc;
			try {
				Object arg = beanFactory
                    .resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
				if (arg == null && !this.required) {
					arguments = null;
					break;
				}
				arguments[i] = arg;
			} catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(
                    		null, beanName, new InjectionPoint(methodParam), ex);
			}
		}
		synchronized (this) {
			if (!this.cached) {
				if (arguments != null) {
					DependencyDescriptor[] cachedMethodArguments =
                        	Arrays.copyOf(descriptors, arguments.length);
					registerDependentBeans(beanName, autowiredBeans);
					if (autowiredBeans.size() == argumentCount) {
						Iterator<String> it = autowiredBeans.iterator();
						Class<?>[] paramTypes = method.getParameterTypes();
						for (int i = 0; i < paramTypes.length; i++) {
							String autowiredBeanName = it.next();
							if (beanFactory.containsBean(autowiredBeanName) &&
									beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
								cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
										descriptors[i], autowiredBeanName, paramTypes[i]);
							}
						}
					}
					this.cachedMethodArguments = cachedMethodArguments;
				} else {
					this.cachedMethodArguments = null;
				}
				this.cached = true;
			}
		}
	}
	if (arguments != null) {
		try {
			// 調用目標方法
			ReflectionUtils.makeAccessible(method);
			method.invoke(bean, arguments);
		} catch (InvocationTargetException ex) {
			throw ex.getTargetException();
		}
	}
}

setter方法Autowire

Spring允許使用setter方法進行依賴註入,這種方式需要在註冊BeanDefinition時為其指定AutowireMode參數,有幾個可選的值:

  • AUTOWIRE_NO
  • AUTOWIRE_BY_NAME
  • AUTOWIRE_BY_TYPE
  • AUTOWIRE_CONSTRUCTOR
  • AUTOWIRE_AUTODETECT

例如:

GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(UserService.class);
// 指定使用類型進行依賴註入
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

registry.registerBeanDefinition("userService", beanDefinition);

源碼在populateBean流程中,這個方法的代碼之前記錄過,此處再看一下setter註入的邏輯:

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
	// ... 略

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

	// 此處處理setter方法註入
	// 1. 從Bean類型解析property和對應的setter方法,將property名稱和對應要註入的Bean對象封裝到PropertyValues中
	// 2. 這裡有根據屬性類型和根據屬性名稱註入兩種模式
	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);

	// 調用InstantiationAwareBeanPostProcessor的postProcessProperties方法
	// AutowiredAnnotationBeanPostProcessor處理器可以處理@Autowired和@Value註解,前文詳細介紹了
	PropertyDescriptor[] filteredPds = null;
	if (hasInstAwareBpps) {
		if (pvs == null) {
			pvs = mbd.getPropertyValues();
		}
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					pvsToUse = ibp
                        .postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						return;
					}
				}
				pvs = pvsToUse;
			}
		}
	}
	// 預設false
	if (needsDepCheck) {
		if (filteredPds == null) {
			filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
		}
		checkDependencies(beanName, mbd, filteredPds, pvs);
	}

	// 使用setter方法為屬性註入依賴
	// 不再展開分析
	if (pvs != null) {
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
}

@Bean方法參數Autowire

註冊BeanDefinition

private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
	ConfigurationClass configClass = beanMethod.getConfigurationClass();
	MethodMetadata metadata = beanMethod.getMetadata();
	String methodName = metadata.getMethodName();

	AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);

	// 獲取BeanName和別名
	List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
	String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

	// 註冊別名
	for (String alias : names) {
		this.registry.registerAlias(beanName, alias);
	}

	// 是否覆蓋已存在Bean的判斷,allowBeanDefinitionOverriding屬性用於設置是否允許覆蓋
	// 代碼略

	// 創建BeanDefinition
	ConfigurationClassBeanDefinition beanDef = 
        new ConfigurationClassBeanDefinition(configClass, metadata, beanName);
	beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

	if (metadata.isStatic()) {
		// 靜態方法
		if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {
			beanDef.setBeanClass(
                ((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());
		} else {
			beanDef.setBeanClassName(configClass.getMetadata().getClassName());
		}
		// @Bean方法名
		beanDef.setUniqueFactoryMethodName(methodName);
	} else {
		// 實例方法
		// FactoryBeanName = Configuration類的BeanName
		beanDef.setFactoryBeanName(configClass.getBeanName());
		// @Bean方法名
		beanDef.setUniqueFactoryMethodName(methodName);
	}

	if (metadata instanceof StandardMethodMetadata) {
		beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());
	}

	// 設置AutowireMode = AUTOWIRE_CONSTRUCTOR
	beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.
			SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

	AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

	Autowire autowire = bean.getEnum("autowire");
	if (autowire.isAutowire()) {
		beanDef.setAutowireMode(autowire.value());
	}

	boolean autowireCandidate = bean.getBoolean("autowireCandidate");
	if (!autowireCandidate) {
		beanDef.setAutowireCandidate(false);
	}

	// initMethod及destroyMethod略

	// Scope及Proxy略

	this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

創建實例

上文介紹過,創建Bean實例邏輯在AbstractAutowireCapableBeanFactory類的createBeanInstance方法中,其中這段代碼用於創建@Bean實例:

// 使用工廠創建Bean實例,@Bean註解標註的方法會使用這種方式創建Bean實例
if (mbd.getFactoryMethodName() != null) {
	return instantiateUsingFactoryMethod(beanName, mbd, args);
}

instantiateUsingFactoryMethod方法:

protected BeanWrapper instantiateUsingFactoryMethod(
		String beanName, RootBeanDefinition mbd, Object[] explicitArgs) {
	return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}

instantiateUsingFactoryMethod方法代碼較多,此處簡單介紹一下流程:

  1. 從mbd獲取factoryBeanName即Configuration類的BeanName並從容器裡面獲取這個factoryBean對象
  2. 獲取用來創建Bean的Method候選集
  3. 如果Method候選集只有一個方法且該方法無參數,直接使用這個方法創建Bean
  4. 如果Method候選集有多個方法,排序,參數多的在前面
  5. 遍歷Method候選集,從容器裡面獲取方法參數Bean,選擇最優的Method
  6. 使用最優Method創建Bean

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Go語言流媒體開源項目 [LAL](https://github.com/q191201771/lal) 今天發佈了v0.36.7版本。 > LAL 項目地址:https://github.com/q191201771/lal 老規矩,簡單介紹一下: ▦ Customize Sub,我有的都給你 這 ...
  • 哈嘍大家好,我是鹹魚 我們知道,python 在自動化領域中被廣泛應用,可以很好地自動化處理一些任務 就比如編寫 Python 腳本自動化執行重覆性的任務,如文件處理、數據處理、系統管理等需要運行其他程式或者與操作系統交互的任務 那麼今天我們來看一下在 python 中如何運行 shell 命令來與 ...
  • ThreadLocal(TL)、InheritableThreadLocal(ITL)和TransmittableThreadLocal(TTL)在不同場景下有不同用途,本文我們來分析一下 ...
  • ### 1. 使用方括弧([]):使用方括弧直接訪問字典中的鍵對應的值,示例代碼如下: ```python # 定義一個字典 person = {'name': 'Tom', 'age': 25, 'gender': 'male'} # 使用方括弧訪問指定鍵對應的值 print(person['na ...
  • # 4. 列表 列表非常適合於存儲程式運行期間可能變化的數據集。 ## 遍歷列表 ```py nums = ["alice","david","carolina"] for iter in nums: print(iter) ``` ## 創建數值列表 1、簡單使用range() 函數 ```py ...
  • - 準備環境 1. python3.7+ 2. 依賴:aiohttp - 代碼實現(代理伺服器,返迴響應體和進行跨域處理後的headers) ``` python3.7 import aiohttp from functools import wraps from aiohttp import we ...
  • CheckStyle作為檢驗代碼規範的插件,除了可以使用配置預設給定的開發規範,如Sun的,Google的開發規範啊,也可以導入像阿裡的開發規範的插件。 事實上,每一個公司都存在不同的開發規範要求,所以大部分公司會給定自己的check規範,一般導入給定的 checkstyle.xml 文件即可實現。 ...
  • # AbstractJsonUserAttributeMapper 它是一個抽象類,用來更新條件更新用戶屬性(user_attribute)的信息,我們在實現自己的mapper時,需要關註3個方法,下麵分別介紹一下: ## getCompatibleProviders方法 它用來直指你的mapper ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...