使用Spring 編程時,使用Ioc,我們只需要聲明對象,而由Spring 替我門自動注入,而其中起重要作用則爲 AutowiredAnnotationBeanPostProcessor
,它在bean實例化後,進行這重要的初始化操作。
AutowiredAnnotationBeanPostProcessor
支持 @Autowired
和 @Value
註解的支持也支持 @Inject
註解,也可以給setter
方法進行注入。也包括對 @Lookup
註解解析。
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
...
}
AutowiredAnnotationBeanPostProcessor
實現了多個接口及抽象類,重要的爲 InstantiationAwareBeanPostProcessorAdapter
和 MergedBeanDefinitionPostProcessor
等,而 InstantiationAwareBeanPostProcessorAdapter
則爲 SmartInstantiationAwareBeanPostProcessor
類型。
初始化地方
AutowiredAnnotationBeanPostProcessor
是在 AnnotationConfigApplicationContext
初始化時就被加入到 BeanFactory
中,所以所有bean被加載時候,都會執行這個 PostProcessor
。
在初始化 AnnotationConfigApplicationContext
時候,會網beanDefs中加入一些默認配置bean:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
:對應ConfigurationClassPostProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
對應AutowiredAnnotationBeanPostProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor"
對應CommonAnnotationBeanPostProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
對應org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
org.springframework.context.event.internalEventListenerProcessor
對應EventListenerMethodProcessor
org.springframework.context.event.internalEventListenerFactory
對應DefaultEventListenerFactory
determineCandidateConstructors
首先從實例化開始,對上一篇中 getBean
的 createBeanInstance
進行進一步分析,當一個bean的構造方法爲多個參數,且 參數有用 @Autowired
時候,則需要判斷參數是否需要 autowired
。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
...
// Candidate constructors for autowiring?
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
..
}
而 具體則利用 postProcessor
去分析:
@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
// 判斷是否有初始化前後調用的postprocessors
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
// 執行所有的 SmartInstantiationAwareBeanPostProcessor
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
// 找到第一個不爲空的則返回
return ctors;
}
}
}
}
return null;
}
接下來看重點方法: AutowiredAnnotationBeanPostProcessor
的 determineCandidateConstructors
:
@Override
@Nullable
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// 檢查是否有 lookup,如果沒有則進入
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
// 對所有 方法執行 lambd邏輯
ReflectionUtils.doWithMethods(beanClass, method -> {
// 看是否 有lookUp邏輯
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
// 如果最終有 @Lookup修飾
Assert.state(this.beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
// 將override方法註冊進 BeanDefinition
RootBeanDefinition mbd = (RootBeanDefinition) this.beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
// 並將它加入到 lookupMethodsChecked 中
this.lookupMethodsChecked.add(beanName);
}
// 首先從緩存中拿,看是否能拿到
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
// 完全加鎖
synchronized (this.candidateConstructorsCache) {
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
Constructor<?>[] rawCandidates;
try {
// 獲取所有的構造方法,如果未聲明,則會獲取到一個默認的構造方法
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;
// 適配 Kotlin,其他類則只返回null
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
int nonSyntheticConstructors = 0;
for (Constructor<?> candidate : rawCandidates) {
if (!candidate.isSynthetic()) {
// 如果不是 synthetic,則自增
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
// 從該 構造方法中,獲取註解信息
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann == null) {
// 如果自身沒有使用 @Autowired或者 @Value修飾的,則看其父類是否有。
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) {
// 如果自己沒有需要@Autowried的,但是父類有,那麼一場了。
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
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;
}
// 只有當需要@Autowired 則需要加入到候選中
candidates.add(candidate);
}
else if (candidate.getParameterCount() == 0) {
// 如果參數個數爲0,則保存默認的構造方法
defaultConstructor = candidate;
}
}
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
if (requiredConstructor == null) {
if (defaultConstructor != null) {
candidates.add(defaultConstructor);
}
else if (candidates.size() == 1 && logger.isInfoEnabled()) {
logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
"': single autowire-marked constructor flagged as optional - " +
"this constructor is effectively required since there is no " +
"default constructor to fall back to: " + candidates.get(0));
}
}
candidateConstructors = candidates.toArray(new Constructor<?>[0]);
}
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
candidateConstructors = new Constructor<?>[] {primaryConstructor};
}
else {
// 如果是無參構造方法,默認則爲空數組
candidateConstructors = new Constructor<?>[0];
}
// 將候選構造方法,都放入 candidateConstructorsCache 中。
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
// 返回構造方法
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
- 再一次檢查所有方法是否包含
@Lookup
註解,有就放入lookupMethodsChecked
中 。 - 檢查構造方法,並且看構造方法中,是否有
@Autowired
或@Value
修飾。如果有則會加入到candidateConstructorsCache
中。
findAutowiredAnnotation
即爲獲取所有參數,看是否有 用 @Autowired
或 @Value
修飾參數:
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
if (ao.getAnnotations().length > 0) { // autowiring annotations have to be local
// 此時 autowiredAnnotationTypes 只有兩個字段,@Autowired 和 @Value
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
if (attributes != null) {
return attributes;
}
}
}
return null;
}
- 如果是無參構造方法,則會返回null,有參則會返回所有構造方法。
autowireConstructor
從上面獲取構造方法,如果有 多參構造方法,且有 需要 @Autowried
的, 則會進入 AbstractAutowireCapableBeanFactory
:
// Candidate constructors for autowiring?
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 有多參構造方法,且有@Autowired 方法註釋
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
autowireConstructor:
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
postProcessMergedBeanDefinition
這是主要注入方法,在 上面獲取完構造方法後,則會進行實例化,而實例化完之後,Spring 同樣提供了 模塊從而可以進行對bean實例化後的初始化操作,具體調用點在 doCreateBean
-> applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
這樣依賴,所有 MergedBeanDefinitionPostProcessor
均可以執行,從而會到 AutowiredAnnotationBeanPostProcessor
中的 postProcessMergedBeanDefinition
:
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
findAutowiringMetadata
:獲取 所 有@Autowired
和@Value
數據,而後封裝 放入injectionMetadataCache
中。實際主題方法則是在buildAutowiringMetadata
中進行。
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// 獲取緩存key
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// 首先從緩存中獲取。
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
// metadata==null或者clazz和 當前類不一致,則會進來
synchronized (this.injectionMetadataCache) {
// 再嘗試獲取一次
metadata = this.injectionMetadataCache.get(cacheKey);
// 在檢查一次
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
// 構建Autowiring數據
metadata = buildAutowiringMetadata(clazz);
// 存入緩存,即beanName, reference
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
buildAutowiringMetadata
:搜尋所有 非靜態且有@Autowired
和@Value
註解的方法和字段。
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
// 對所有的字段進行處理
ReflectionUtils.doWithLocalFields(targetClass, field -> {
// 獲取該字段上面的@Autowired和 @Value註解
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
// 不支持 靜態變量
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
// 判斷註解上require類型
boolean required = determineRequiredStatus(ann);
// 將其加入到 currElements中
currElements.add(new AutowiredFieldElement(field, required));
}
});
// 對所有方法進行注入
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
// 如果方法不可見,則返回
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
// 獲取方法註解
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
// 同樣不支持靜態注入
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
}
return;
}
// 如果沒有參數,則會警告,因爲必須要有一個參數來注入。
if (method.getParameterCount() == 0) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
// 獲取注入的方法所需的參數。
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
// 加入 currElements 中。
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
//
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
// 往上尋找
while (targetClass != null && targetClass != Object.class);
// 構造InjectionMetadata返回
return new InjectionMetadata(clazz, elements);
}
很明顯,Spring不支持靜態方法和類的注入,但是卻可以通過別的方法進行注入,例如:
@Component("NewClass")
public class NewClass{
private static SomeThing someThing;
@Autowired
public void setSomeThing(SomeThing someThing){
NewClass.someThing = someThing;
}
}
或者使用 @PostConstruct
進行注入。
@Component
public class TestClass {
private static AutowiredTypeComponent component;
@Autowired
private AutowiredTypeComponent autowiredComponent;
@PostConstruct
private void init() {
component = this.autowiredComponent;
}
public static void testMethod() {
component.callTestMethod();
}
}
但是,並不推薦這樣做,因爲一個實例一旦是 static類型,那麼它就脫離了Spring 容器管轄,它屬於整個類了。
postProcessMergedBeanDefinition
中 第一行已分析完,主要功能就是獲取所有 @Autowired
\ @Value
的類和方法。下面看 checkConfigMembers
方法:
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
// injectedElements 則爲上一步中獲取的所有待注入的字段和方法
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
// 如果該字段沒有交由Spring 管理。
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
beanDefinition.registerExternallyManagedConfigMember(member);
// 將其加入到 checkedElements 中
checkedElements.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}
checkConfigMembers
重點在於對上一步中找到的所有 待注入的方法,並將其加入到 beanDefinition中externallyManagedConfigMembers
和 checkedElements
中。
整個 postProcessMergedBeanDefinition
並沒有對內部靜態變量進行賦值,而僅僅找出所有的 待注入類,存入了AutowiredAnnotationBeanPostProcessor
中。
postProcessProperties
整個實際的注入過程,則是在 postProcessProperties
中。而目前 外部調用處則只有 doCreateBean
中的 popularBean
方法。
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 找到所有注入數據。popularBean 中 在前一步已經緩存了,具體調用爲 postProcessMergedBeanDefinition 方法
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;
}
- 找到所有注入數據。
popularBean
中 在前一步已經緩存了,具體調用爲postProcessMergedBeanDefinition
方法 - 具體注入邏輯 則在
metadata.inject(bean, beanName, pvs);
。
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 獲取所有待注入數據
Collection<InjectedElement> checkedElements = this.checkedElements;
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);
}
}
}
上面獲取到每個元素(InjectedElement
)後,則執行其自身 inject
方法,而 pvs則爲傳入參數,可配置鍵值對。
InjectedElement
爲 InjectionMetadata
內部類,代表着待注入的元素,而 InjectedElement
實現類有
前兩種則代表着注入方法和注入字段,後面幾種則以後慢慢分析。
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 獲取當前field
Field field = (Field) this.member;
Object value;
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
// 設置 beanClass
desc.setContainingClass(bean.getClass());
// 用來存儲候選的類
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// 主題獲取方法,從beanFactory中獲取對應 DependencyDescriptor 所需beanInstance
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
// 在 beanFactory中註冊 register bean。
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
// 緩存起來。
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
// 使用 反射設置。
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
- 獲取當前
InjectedElement
鎖需要注入的bean類型DependencyDescriptor
。 - 調用
beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter)
獲取對應 依賴的 bean名稱
根據不同類型的註解進行處理。 - 將獲取到的bean 實例,注入到 beanFactory的 dependentBeans中。
- 將 獲取的 bean 實例,放入
cachedFieldValue
中緩存。 - 最後調用反射,給該字段設值。
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
// 設置 parameterNameDiscoverer
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
if (Optional.class == descriptor.getDependencyType()) {
// 如果是 Optional類型的
return createOptionalDependency(descriptor, requestingBeanName);
}
// ObjectFactory 類型
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
// 使用@Inject註解的
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
// 首先判斷是否有@Lazy註解
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// 普通獲取。
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
- 如果是
@Lazy
註解的注入,則返回的不是具體實例,而是一個代理對象,而當調用具體方法時返回。 - 如果是普通的
@Autowired
註解 ,則主流程在doResolveDependency
中進行,期間包括了對@Qualifier
和@Primary
解析。
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable 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) {
// A custom TypeConverter which does not support TypeDescriptor resolution...
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
// 獲取集合 bean的操作,包含array,Collection,Map等
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
// 獲取其他bean的過程,例如多實例數據庫的操作。這裏有使用 @Qualifier 過濾,即如果使用 @Qualifier ,則會優先處理。
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
// 如果有多個候選實例
if (matchingBeans.size() > 1) {
// 決定使用哪一個,判斷 用到@Primary諸侯選
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
// possibly it was meant to be an empty collection of multiple regular beans
// (before 4.3 in particular when we didn't even look for collection beans).
return null;
}
}
// 直接獲取選擇出的autowiredBeanName
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) {
// 獲取當前字段實例。
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
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);
}
}
上面 doResolveDependency
則包括了主體流程,包括對 @Qualifier
和 @Primary
解析等。
總結
整個 AutowiredAnnotationBeanPostProcessor
作用也好理解,它有以下作用:
determineCandidateConstructors
負責找出具體構造方法,並且判斷構造方法是否需要@Autowired
,而如果有需要構造方法@Autowired
,則需要走另一種邏輯,這個可以看後面的循環依賴解決。postProcessProperties
對所有字段和方法,進行具體注入地方。postProcessMergedBeanDefinition
處理所有使用@Autowired
和@Value
註解方法。
覺得博主寫的有用,不妨關注博主公衆號: 六點A君。
哈哈哈,一起研究Spring: