spring 自動注入AutowiredAnnotationBeanPostProcessor源碼解析
一、MergedBeanDefinitionPostProcessor
1.1、postProcessMergedBeanDefinition
在Bean屬性賦值前,緩存屬性字段上的@Autowired和@Value注解信息。
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
//1.1.1 查詢屬性或方法上有@Value和@Autowired注解的元素
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
//1.1.2 檢查元數(shù)據(jù)信息
metadata.checkConfigMembers(beanDefinition);
}
1.1.1 findAutowiringMetadata 查詢屬性或方法上有@Value和@Autowired注解的元素
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.
//獲取Bean名稱作為緩存key
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
//使用雙重檢查機(jī)制獲取緩存
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
//判斷是否有元數(shù)據(jù)
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
//構(gòu)建元數(shù)據(jù)
metadata = buildAutowiringMetadata(clazz);
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
這個 do-while 循環(huán)是用來一步一步往父類上爬的(可以看到這個循環(huán)體的最后一行是獲取父類,判斷條件是判斷是否爬到了 Object)
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
// 判斷是不是候選者類,比如說類名是以 java.開頭的則不是候選者類 Order的實(shí)現(xiàn)類也不是候選者類
// 但是如果this.autowiredAnnotationTypes 中有以java.開頭的注解就返回true了
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<>();
// 循環(huán)獲取類上的屬性,如果類屬性上有@Value和@Autowired包裝成AutowiredFieldElement放入結(jié)果集
ReflectionUtils.doWithLocalFields(targetClass, field -> {
MergedAnnotation<?> 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;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
// 循環(huán)獲取類上的方法,如果類方法上有@Value和@Autowired包裝成AutowiredMethodElement放入結(jié)果集
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())) {
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.add(new AutowiredMethodElement(method, required, pd));
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return InjectionMetadata.forElements(elements, clazz);
}
1.1.2 檢查元數(shù)據(jù)信息
檢查是否有重復(fù)的元數(shù)據(jù),去重處理,如一個屬性上既有@Autowired注解,又有@Resource注解 。只使用一種方式進(jìn)行注入,由于@Resource先進(jìn)行解析,所以會選擇@Resource的方式
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}
二、SmartInstantiationAwareBeanPostProcessor
2.1、determineCandidateConstructors
在bean實(shí)例化前選擇@Autowired注解的構(gòu)造函數(shù),同時注入屬性,從而完成自定義構(gòu)造函數(shù)的選擇。
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// Let's check for lookup methods here...
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
ReflectionUtils.doWithMethods(beanClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
Assert.state(this.beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
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);
}
this.lookupMethodsChecked.add(beanName);
}
// 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 {
//反射獲取所有構(gòu)造函數(shù)
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);
}
//候選構(gòu)造方法
List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
Constructor<?> requiredConstructor = null;
Constructor<?> defaultConstructor = null;
//這個貌似是 Kotlin 上用的, 不用管它
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
int nonSyntheticConstructors = 0;
//遍歷這些構(gòu)造函數(shù)
for (Constructor<?> candidate : rawCandidates) {
//判斷構(gòu)造方法是否是合成的
if (!candidate.isSynthetic()) {
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
//查看是否有 @Autowired 注解
//如果有多個構(gòu)造方法, 可以通過標(biāo)注 @Autowired 的方式來指定使用哪個構(gòu)造方法
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann == null) {
Class<?> userClass = ClassUtils.getUserClass(beanClass);
if (userClass != beanClass) {
try {
Constructor<?> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
ann = findAutowiredAnnotation(superCtor);
}
catch (NoSuchMethodException ex) {
// Simply proceed, no equivalent superclass constructor found...
}
}
}
//有 @Autowired 的情況
if (ann != null) {
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;
}
candidates.add(candidate);
}
//無參構(gòu)造函數(shù)的情況
else if (candidate.getParameterCount() == 0) {
//構(gòu)造函數(shù)沒有參數(shù), 則設(shè)置為默認(rèn)的構(gòu)造函數(shù)
defaultConstructor = candidate;
}
}
//到這里, 已經(jīng)循環(huán)完了所有的構(gòu)造方法
//候選者不為空時
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]);
}
//類的構(gòu)造方法只有1個, 且該構(gòu)造方法有多個參數(shù)
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
//這里不會進(jìn), 因?yàn)?primaryConstructor = null
else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
//這里也不會進(jìn), 因?yàn)?primaryConstructor = null
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
candidateConstructors = new Constructor<?>[] {primaryConstructor};
}
else {
//如果方法進(jìn)了這里, 就是沒找到合適的構(gòu)造方法
//1. 類定義了多個構(gòu)造方法, 且沒有 @Autowired , 則有可能會進(jìn)這里
candidateConstructors = new Constructor<?>[0];
}
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
//這里如果沒找到, 則會返回 null, 而不會返回空數(shù)組
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
遍歷構(gòu)造方法:
- 只有一個無參構(gòu)造方法, 則返回null
- 只有一個有參構(gòu)造方法, 則返回這個構(gòu)造方法
- 有多個構(gòu)造方法且沒有@Autowired, 此時spring則會蒙圈了, 不知道使用哪一個了。這里的后置處理器智能選擇構(gòu)造方法后置處理器。當(dāng)選擇不了的時候, 干脆返回 null
- 有多個構(gòu)造方法, 且在其中一個方法上標(biāo)注了 @Autowired , 則會返回這個標(biāo)注的構(gòu)造方法
- 有多個構(gòu)造方法, 且在多個方法上標(biāo)注了@Autowired, 則spring會拋出異常, Spring會認(rèn)為, 你指定了幾個給我, 是不是你弄錯了
注意:
這地方有個問題需要注意一下, 如果你寫了多個構(gòu)造方法, 且沒有寫 無參構(gòu)造方法, 那么此處返回null,
在回到 createBeanInstance 方法中, 如果不能走 autowireConstructor(), 而走到 instantiateBean() 中去的話, 會報錯的,因?yàn)轭愐呀?jīng)沒有無參構(gòu)造函數(shù)了。
以上就是AutowiredAnnotationBeanPostProcessor源碼解析的詳細(xì)內(nèi)容,更多關(guān)于AutowiredAnnotationBeanPostProcessor的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決Javaweb 提交表單到servlet時出現(xiàn)空白頁面,但網(wǎng)站不報錯問題
這篇文章主要介紹了解決Javaweb 提交表單到servlet時出現(xiàn)空白頁面,但網(wǎng)站不報錯的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
java獲取機(jī)器碼簡單實(shí)現(xiàn)demo
這篇文章主要為大家介紹了java獲取機(jī)器碼的簡單實(shí)現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
解決java.util.NoSuchElementException異常的問題
這篇文章主要介紹了解決java.util.NoSuchElementException異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式
這篇文章主要介紹了詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

