欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring 自動注入AutowiredAnnotationBeanPostProcessor源碼解析

 更新時間:2023年03月07日 11:06:35   作者:無名之輩J  
這篇文章主要介紹了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.
   //使用雙重檢查機制獲取緩存
   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的實現(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ù)信息

檢查是否有重復的元數(shù)據(jù),去重處理,如一個屬性上既有@Autowired注解,又有@Resource注解 。只使用一種方式進行注入,由于@Resource先進行解析,所以會選擇@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實例化前選擇@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)造方法, 可以通過標注 @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è)置為默認的構(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]};
                    }
                    //這里不會進, 因為 primaryConstructor = null
                    else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
                            defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                        candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
                    }
                    //這里也不會進, 因為 primaryConstructor = null
                    else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                        candidateConstructors = new Constructor<?>[] {primaryConstructor};
                    }
                    else {
                        //如果方法進了這里, 就是沒找到合適的構(gòu)造方法
                        //1. 類定義了多個構(gòu)造方法, 且沒有 @Autowired , 則有可能會進這里
                        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)造方法后置處理器。當選擇不了的時候, 干脆返回 null
  • 有多個構(gòu)造方法, 且在其中一個方法上標注了 @Autowired , 則會返回這個標注的構(gòu)造方法
  • 有多個構(gòu)造方法, 且在多個方法上標注了@Autowired, 則spring會拋出異常, Spring會認為, 你指定了幾個給我, 是不是你弄錯了

注意:

這地方有個問題需要注意一下, 如果你寫了多個構(gòu)造方法, 且沒有寫 無參構(gòu)造方法, 那么此處返回null, 

在回到 createBeanInstance 方法中, 如果不能走 autowireConstructor(), 而走到 instantiateBean() 中去的話, 會報錯的,因為類已經(jīng)沒有無參構(gòu)造函數(shù)了。

以上就是AutowiredAnnotationBeanPostProcessor源碼解析的詳細內(nèi)容,更多關(guān)于AutowiredAnnotationBeanPostProcessor的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 解決Javaweb 提交表單到servlet時出現(xiàn)空白頁面,但網(wǎng)站不報錯問題

    解決Javaweb 提交表單到servlet時出現(xiàn)空白頁面,但網(wǎng)站不報錯問題

    這篇文章主要介紹了解決Javaweb 提交表單到servlet時出現(xiàn)空白頁面,但網(wǎng)站不報錯的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Mybatis中流式查詢的實現(xiàn)示例

    Mybatis中流式查詢的實現(xiàn)示例

    MyBatis的ResultHandler是用于處理數(shù)據(jù)庫查詢結(jié)果集的工具,可以通過回調(diào)函數(shù)對數(shù)據(jù)進行流式處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-09-09
  • java獲取機器碼簡單實現(xiàn)demo

    java獲取機器碼簡單實現(xiàn)demo

    這篇文章主要為大家介紹了java獲取機器碼的簡單實現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-11-11
  • Java創(chuàng)建線程及配合使用Lambda方式

    Java創(chuàng)建線程及配合使用Lambda方式

    這篇文章主要介紹了Java創(chuàng)建線程及配合使用Lambda方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • java使用枚舉封裝錯誤碼及錯誤信息詳解

    java使用枚舉封裝錯誤碼及錯誤信息詳解

    這篇文章主要介紹了java使用枚舉封裝錯誤碼及錯誤信息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 解決java.util.NoSuchElementException異常的問題

    解決java.util.NoSuchElementException異常的問題

    這篇文章主要介紹了解決java.util.NoSuchElementException異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • java中字符串與日期的轉(zhuǎn)換實例

    java中字符串與日期的轉(zhuǎn)換實例

    java中字符串與日期的轉(zhuǎn)換實例,需要的朋友可以參考一下
    2013-05-05
  • Java規(guī)則引擎Easy Rules的使用介紹

    Java規(guī)則引擎Easy Rules的使用介紹

    這篇文章主要介紹了Java規(guī)則引擎Easy Rules的使用介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • 淺談java泛型的作用及其基本概念

    淺談java泛型的作用及其基本概念

    下面小編就為大家?guī)硪黄獪\談java泛型的作用及其基本概念。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • 詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式

    詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式

    這篇文章主要介紹了詳解Mybatis多參數(shù)傳遞入?yún)⑺姆N處理方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04

最新評論