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() 中去的話, 會報錯的.
因為類已經沒有無參建構式了
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/131441.html
標籤:Java
