溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

spring自動注入AutowiredAnnotationBeanPostProcessor源碼分析

發(fā)布時間:2023-03-07 14:01:31 來源:億速云 閱讀:91 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“spring自動注入AutowiredAnnotationBeanPostProcessor源碼分析”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

    一、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ù)了。

    “spring自動注入AutowiredAnnotationBeanPostProcessor源碼分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI