1. 程式人生 > 實用技巧 >Bean後置處理器 - SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors

Bean後置處理器 - SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors

spring在建立物件(org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance)的時候, 使用了這個 建構函式後置處理器, 用來選擇使用哪個建構函式的.

所以這個後置處理器的執行時機是: 物件例項化之前執行

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null
) { return ctors; } } } } return null; }

這裡滿足條件的後置處理器, 就兩個:

1.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

2.AutowiredAnnotationBeanPostProcessor

ImportAwareBeanPostProcessor

@Override
@Nullable
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
    return null;
}

這個類並沒有實現這個介面, 而是父類去實現的:

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter#determineCandidateConstructors

然而, 他也是 啥也沒幹.

怎麼感覺這個後置處理器, 哪哪都有他, 卻哪哪都不幹活.

AutowiredAnnotationBeanPostProcessor

@Override
@Nullable
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 {
                    //反射獲取所有建構函式
                    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 上用的, 不用管它
                Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                int nonSyntheticConstructors = 0;
                //遍歷這些建構函式
                for (Constructor<?> candidate : rawCandidates) {
                    //判斷構造方法是否是合成的
                    if (!candidate.isSynthetic()) {
                        nonSyntheticConstructors++;
                    }
                    else if (primaryConstructor != null) {
                        continue;
                    }
                    //檢視是否有 @Autowired 註解
                    //如果有多個構造方法, 可以通過標註 @Autowired 的方式來指定使用哪個構造方法
                    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);
                    }
                    //無參建構函式的情況
                    else if (candidate.getParameterCount() == 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]);
                }
                //類的構造方法只有1個, 且該構造方法有多個引數
                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 {
                    //如果方法進了這裡, 就是沒找到合適的構造方法
                    //1. 類定義了多個構造方法, 且沒有 @Autowired , 則有可能會進這裡
                    candidateConstructors = new Constructor<?>[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
   //這裡如果沒找到, 則會返回 null, 而不會返回空陣列
return (candidateConstructors.length > 0 ? candidateConstructors : null); }

這個方法比較長, 但是仔細看, 是能看懂的. 大致可以劃分為幾個步驟:

1. 獲取類的所有構造方法

2. 遍歷構造方法

  |-> 只有一個無參構造方法, 則返回null

  |-> 只有一個有參構造方法, 則返回這個構造方法

  |-> 有多個構造方法且沒有@Autowired, 此時spring則會蒙圈了, 不知道使用哪一個了. 這裡的後置處理器, 翻譯過來, 叫智慧選擇構造方法後置處理器.

    當選擇不了的時候, 乾脆返回 null

  |-> 有多個構造方法, 且在其中一個方法上標註了 @Autowired , 則會返回這個標註的構造方法

  |-> 有多個構造方法, 且在多個方法上標註了@Autowired, 則spring會丟擲異常, spring會認為, 你指定了幾個給我, 是不是你弄錯了

注:

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

在回到createBeanInstance 方法中, 如果不能走autowireConstructor(), 而走到instantiateBean() 中去的話, 會報錯的.

因為類已經沒有無參構造函數了