今天在研究代碼的過程中發現@Value 注解也走的是@Autowired 自動注入的流程, 接下來研究@Autowired 和 @Resource 的邏輯。
1. 自動注入
這里的自動注入說的是setter修飾的屬性的自動注入,和@Autowired、@Resource 修飾的屬性無關。兩個的邏輯走的不是一套。
0. 前置
在Spring 反射創建對象和屬性注入過程中有個重要的后置處理器InstantiationAwareBeanPostProcessor, 可以理解為對象創建后置處理器。
package org.springframework.beans.factory.config; import java.beans.PropertyDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.lang.Nullable; public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor { // 反射創建對象前調用,調用時機是在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[]); 如果返回不為null, 則使用返回的對象作為容器生產的對象,也不會走該bean 的屬性注入等過程 @Nullable default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { return null; } // 反射創建完對象之后、屬性注入 之前調用 default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { return true; } // 獲取到需要注入的屬性(@Autowired 和 @Resource 屬性不在pvs 內部)之后、屬性注入之前進行調用, @Autowired 和 @Resource 是在該方法內進行注入 @Nullable default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { return null; } // 同上面一樣,加了屬性描述符 /** @deprecated */ @Deprecated @Nullable default PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { return pvs; } }
這個后置處理器是在對象創建前后進行調用。 其邏輯可以理解為
1》對象創建前調用 postProcessBeforeInstantiation (相當於提供了自己創建對象的接口),返回不為null,則不走后續反射以及屬性注入流程;
2》創建后調用populateBean 方法,方法內部主要邏輯是:
2.1》調用 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation 處理對象創建后邏輯;
2.2》然后獲取從beanDefinition的map 獲取需要注入的屬性,並且維護到PropertyValue 中
2.3》 調用 InstantiationAwareBeanPostProcessor.postProcessProperties 處理解析出的屬性 (@Autowired 和 @Resource 是在這一步操作,其沒有對PropertyValue 做處理,只是掃描相關注解反射進行注入 )
2.4》 調用 applyPropertyValues 方法 將上面的PropertyValue 進行反射 方法注入
1. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[]) 這里是創建對象的開始
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } }
1》 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null) { bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; } protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { return result; } } } return null; } public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
這個就相當於可以通過org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 手動根據類型與BeanName 返回一個對象; 返回之后跳過一些屬性注入過程和初始化過程,直接調用org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization 初始化之后方法
2. 如果上面 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation 沒有手動創建對象就進行下面操作
1》org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 走Spring 創建對象的生命周期
2》 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean:

/** * Populate the bean instance in the given BeanWrapper with the property values * from the bean definition. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @param bw the BeanWrapper with bean instance */ @SuppressWarnings("deprecation") // for postProcessPropertyValues protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // 檢測 mbd 合法性 if (bw == null) { if (mbd.hasPropertyValues()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 執行 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation, 也就是對象創建完成之后的邏輯。 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 進行自動注入,這里的自動注入是不在 org.springframework.beans.factory.support.AbstractBeanDefinition#propertyValues 維護的,也就是有setter 方法的。默認的注入模式是NO,現在只支持兩種。BY_NAME 和 BY_TYPE int resolvedAutowireMode = mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 處理屬性,Autowired 和 Resource 在這一步進行處理 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } if (needsDepCheck) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } checkDependencies(beanName, mbd, filteredPds, pvs); } if (pvs != null) { // 應用解析出來的屬性, 調用setter 方法進行自動注入 applyPropertyValues(beanName, mbd, bw, pvs); } } protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } Set<String> autowiredBeanNames = new LinkedHashSet<>(4); String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. if (Object.class != pd.getPropertyType()) { MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered); DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } } protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { if (containsBean(propertyName)) { Object bean = getBean(propertyName); pvs.add(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
上面可以理解為兩步重要步驟,
第一步是根據自動注入模式獲取屬性;(這里的屬性不是@Autowired或者@Resource 指定的屬性,是setter 方法修飾的普通屬性)
第二步是InstantiationAwareBeanPostProcessor#postProcessProperties 處理屬性 (@Autowired、@Resource、@Value 都是這一步完成的)
第三步:調用 applyPropertyValues 進行屬性賦值
關於自動注入的模式有下面幾種:
// 不進行自動注入 int AUTOWIRE_NO = 0; // 根據name去容器找 int AUTOWIRE_BY_NAME = 1; // 根據類型去容器找 int AUTOWIRE_BY_TYPE = 2; // 從構造函數進行注入 int AUTOWIRE_CONSTRUCTOR = 3; /** @deprecated */ // 自動發現 @Deprecated int AUTOWIRE_AUTODETECT = 4;
默認是AUTOWIRE_NO , 也就是認為屬性不需要注入。AUTOWIRE_AUTODETECT 的機制是先找構造如果有參數為0的構造就走根據類型找, 如果不存在無參構造就走構造注入。org.springframework.beans.factory.support.AbstractBeanDefinition#getResolvedAutowireMode:
public int getResolvedAutowireMode() { if (this.autowireMode == AUTOWIRE_AUTODETECT) { // Work out whether to apply setter autowiring or constructor autowiring. // If it has a no-arg constructor it's deemed to be setter autowiring, // otherwise we'll try constructor autowiring. Constructor<?>[] constructors = getBeanClass().getConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterCount() == 0) { return AUTOWIRE_BY_TYPE; } } return AUTOWIRE_CONSTRUCTOR; } else { return this.autowireMode; } }
注意這個自動注入的模式是在BeanDefinition 中存的,如果通過@Bean 注入,可以手動指定:org.springframework.context.annotation.Bean 如下:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Bean { /** * Alias for {@link #name}. * <p>Intended to be used when no other attributes are needed, for example: * {@code @Bean("customBeanName")}. * @since 4.3.3 * @see #name */ @AliasFor("name") String[] value() default {}; /** * The name of this bean, or if several names, a primary bean name plus aliases. * <p>If left unspecified, the name of the bean is the name of the annotated method. * If specified, the method name is ignored. * <p>The bean name and aliases may also be configured via the {@link #value} * attribute if no other attributes are declared. * @see #value */ @AliasFor("value") String[] name() default {}; /** * Are dependencies to be injected via convention-based autowiring by name or type? * <p>Note that this autowire mode is just about externally driven autowiring based * on bean property setter methods by convention, analogous to XML bean definitions. * <p>The default mode does allow for annotation-driven autowiring. "no" refers to * externally driven autowiring only, not affecting any autowiring demands that the * bean class itself expresses through annotations. * @see Autowire#BY_NAME * @see Autowire#BY_TYPE * @deprecated as of 5.1, since {@code @Bean} factory method argument resolution and * {@code @Autowired} processing supersede name/type-based bean property injection */ @Deprecated Autowire autowire() default Autowire.NO; /** * Is this bean a candidate for getting autowired into some other bean? * <p>Default is {@code true}; set this to {@code false} for internal delegates * that are not meant to get in the way of beans of the same type in other places. * @since 5.1 */ boolean autowireCandidate() default true; /** * The optional name of a method to call on the bean instance during initialization. * Not commonly used, given that the method may be called programmatically directly * within the body of a Bean-annotated method. * <p>The default value is {@code ""}, indicating no init method to be called. * @see org.springframework.beans.factory.InitializingBean * @see org.springframework.context.ConfigurableApplicationContext#refresh() */ String initMethod() default ""; /** * The optional name of a method to call on the bean instance upon closing the * application context, for example a {@code close()} method on a JDBC * {@code DataSource} implementation, or a Hibernate {@code SessionFactory} object. * The method must have no arguments but may throw any exception. * <p>As a convenience to the user, the container will attempt to infer a destroy * method against an object returned from the {@code @Bean} method. For example, given * an {@code @Bean} method returning an Apache Commons DBCP {@code BasicDataSource}, * the container will notice the {@code close()} method available on that object and * automatically register it as the {@code destroyMethod}. This 'destroy method * inference' is currently limited to detecting only public, no-arg methods named * 'close' or 'shutdown'. The method may be declared at any level of the inheritance * hierarchy and will be detected regardless of the return type of the {@code @Bean} * method (i.e., detection occurs reflectively against the bean instance itself at * creation time). * <p>To disable destroy method inference for a particular {@code @Bean}, specify an * empty string as the value, e.g. {@code @Bean(destroyMethod="")}. Note that the * {@link org.springframework.beans.factory.DisposableBean} callback interface will * nevertheless get detected and the corresponding destroy method invoked: In other * words, {@code destroyMethod=""} only affects custom close/shutdown methods and * {@link java.io.Closeable}/{@link java.lang.AutoCloseable} declared close methods. * <p>Note: Only invoked on beans whose lifecycle is under the full control of the * factory, which is always the case for singletons but not guaranteed for any * other scope. * @see org.springframework.beans.factory.DisposableBean * @see org.springframework.context.ConfigurableApplicationContext#close() */ String destroyMethod() default AbstractBeanDefinition.INFER_METHOD; }
3. 測試:
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; public class Class1 { @Autowired private Class3 class3; private Class2 class2OldValue; private String name; public void setName(String name) { System.out.println("cn.qlq.dubbo.injecttest.Class1.setName\t" + name); this.name = name; } public void setClass2OldValue(Class2 class2) { System.out.println("cn.qlq.dubbo.injecttest.Class1.setClass2OldValue\t" + class2); this.class2OldValue = class2; } public void setClass4(Class4 class4) { System.out.println("cn.qlq.dubbo.injecttest.Class1.setClass4\t" + class4); } }
動態注入Spring:
package cn.qlq.dubbo.injecttest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.stereotype.Component; @Component public class MyBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Class1.class.getName()); // 下面加了一個引用類型的注入,一個普通數據的注入 beanDefinitionBuilder.addPropertyReference("class2OldValue", "class2"); // class2 是注入到容器中beanName beanDefinitionBuilder.addPropertyValue("name", "beanName-class1"); // 剩余的屬性按照類型自動注入(這個只限定class4 屬性有效) beanDefinitionBuilder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); // 動態注冊到容器 beanDefinitionRegistry.registerBeanDefinition("class1", beanDefinitionBuilder.getBeanDefinition()); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { } }
debug查看上面 populateBean 源碼:
1》 pvs 如下: 這兩個是beanDefinitionBuilder.addPropertyXXX 添加進來的
2》autowireByType 方法內部獲取到的propertyNames 屬性如下
然后解析到之后添加到上面的 pvs 屬性中
3》applyPropertyValues 方法參數上的psv如下: 這一步就是遍歷這個屬性集合,然后調用setter 方法設置值
下面研究@Autowired和@Resource 的注入過程。
2. 前置理解
屬性注入開始時間是在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 屬性設置過程中。其利用的也是后置處理器,在populateBean方法中獲取到所有的后置處理器,然后判斷如果是 InstantiationAwareBeanPostProcessor 類型,則調用 postProcessProperties 進行屬性注入。這需要用到 InstantiationAwareBeanPostProcessor 重要的后置處理器:
其實@Resource和@Autowired(@Value) 用的分別是CommonAnnotationBeanPostProcessor 和 AutowiredAnnotationBeanPostProcessor。
繼承圖如下:
1. CommonAnnotationBeanPostProcessor:處理@Resource
static { try { @SuppressWarnings("unchecked") Class<? extends Annotation> clazz = (Class<? extends Annotation>) ClassUtils.forName("javax.xml.ws.WebServiceRef", CommonAnnotationBeanPostProcessor.class.getClassLoader()); webServiceRefClass = clazz; } catch (ClassNotFoundException ex) { webServiceRefClass = null; } try { @SuppressWarnings("unchecked") Class<? extends Annotation> clazz = (Class<? extends Annotation>) ClassUtils.forName("javax.ejb.EJB", CommonAnnotationBeanPostProcessor.class.getClassLoader()); ejbRefClass = clazz; } catch (ClassNotFoundException ex) { ejbRefClass = null; } resourceAnnotationTypes.add(Resource.class); if (webServiceRefClass != null) { resourceAnnotationTypes.add(webServiceRefClass); } if (ejbRefClass != null) { resourceAnnotationTypes.add(ejbRefClass); } }
2. AutowiredAnnotationBeanPostProcessor 處理@Autowired和@Resource
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#AutowiredAnnotationBeanPostProcessor 默認創建指定其處理的注解:
public AutowiredAnnotationBeanPostProcessor() { this.autowiredAnnotationTypes.add(Autowired.class); this.autowiredAnnotationTypes.add(Value.class); try { this.autowiredAnnotationTypes.add((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader())); logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring"); } catch (ClassNotFoundException ex) { // JSR-330 API not available - simply skip. } }
3. 測試
Class1: 核心類的相關注入如下,接下來主要研究其注入過程。
package cn.qz.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component public class Class1 { @Autowired private Class2 class2; @Resource private Class3 class3; @Value("${server.port}") private String port; private Class5 class5; public Class1(@Autowired Class4 class4) { System.out.println("======class1======"); } @Autowired public void setClass5(Class5 class5) { System.out.println("======setClass5======"); this.class5 = class5; } }
控制台:(如下代表對象創建過程)
======class4====== ======class1====== ======class3====== ======class2====== ======class5====== ======setClass5======
4. 構造注入過程
我們知道Spring 容器bean的生命周期大概可以分為: 注冊beanDefinition -》 反射創建對象 -》 注入bean -》initialing -》 使用 -》 卸載
在構造過程中如果有自動注入的對象,查看其創建過程。
1. 將斷點打到Class4 的構造上,查看調用鏈如下:
2. 過程梳理:
(1) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance 會選擇合適的策略創建對象

/** * Create a new instance for the specified bean, using an appropriate instantiation strategy: * factory method, constructor autowiring, or simple instantiation. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @param args explicit arguments to use for constructor or factory method invocation * @return a BeanWrapper for the new instance * @see #obtainFromSupplier * @see #instantiateUsingFactoryMethod * @see #autowireConstructor * @see #instantiateBean */ protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. Class<?> beanClass = resolveBeanClass(mbd, beanName); if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... boolean resolved = false; boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) { return autowireConstructor(beanName, mbd, null, null); } else { return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring? Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? ctors = mbd.getPreferredConstructors(); if (ctors != null) { return autowireConstructor(beanName, mbd, ctors, null); } // No special handling: simply use no-arg constructor. return instantiateBean(beanName, mbd); }
這里會autowireConstructor(beanName, mbd, ctors, args); 這個代碼塊。 可以看到上面的邏輯是先判斷是否需要自動注入,然后沒有的話走默認的空構造。
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors 這個方法用后置處理器判斷構造方法上是否滿足備選條件:
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; }
最終在這里會委托給org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors 方法,方法內部實際也就是判斷構造上面是否有@Autowired 注解 和 @Value 注解。 最終會委托給org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#findAutowiredAnnotation 判斷是否有注解:
@Nullable private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) { MergedAnnotations annotations = MergedAnnotations.from(ao); for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) { MergedAnnotation<?> annotation = annotations.get(type); if (annotation.isPresent()) { return annotation; } } return null; }
(2) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireConstructor
protected BeanWrapper autowireConstructor( String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) { return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs); }
(3) org.springframework.beans.factory.support.ConstructorResolver#autowireConstructor
(4) org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency
(5) org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency
(6) org.springframework.beans.factory.config.DependencyDescriptor#resolveCandidate
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) throws BeansException { return beanFactory.getBean(beanName); }
相當於先獲取依賴的bean,這樣完成構造注入。
5. 屬性注入的過程
這里修改測試類,@Resource 注入兩個bean,一個根據beanName 能獲取到對象,一個獲取不到:
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component public class Class1 { @Autowired private Class2 class2; @Resource private Class3 class3; @Resource private Class3 class33933; @Value("${server.port}") private String port; @Value("${server.port}") private Integer port1; private Class5 class5; public Class1(@Autowired Class4 class4) { System.out.println("======class1======"); } @Autowired public void setClass5(Class5 class5) { System.out.println("======setClass5======"); this.class5 = class5; } }
1. @Resource 注入過程:
1. spring 容器創建對象過程中org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 方法中會調用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 方法進行對象的屬性注入,該方法內部有如下代碼塊:
PropertyDescriptor[] filteredPds = null; if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } }
這里獲取到的對象后置處理器集合是:
2. 遍歷處理器集合進行判斷,如果是InstantiationAwareBeanPostProcessor 實例就調用postProcessProperties 方法。然后根據結果調用postProcessPropertyValues 方法。然后會調用到org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#postProcessProperties 方法:
@Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex); } return pvs; }
(1) org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#findResourceMetadata 從方法名可以看出來其操作是獲取@Resource 注解聲明的元數據:

1 private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) { 2 // Fall back to class name as cache key, for backwards compatibility with custom callers. 3 String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); 4 // Quick check on the concurrent map first, with minimal locking. 5 InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); 6 if (InjectionMetadata.needsRefresh(metadata, clazz)) { 7 synchronized (this.injectionMetadataCache) { 8 metadata = this.injectionMetadataCache.get(cacheKey); 9 if (InjectionMetadata.needsRefresh(metadata, clazz)) { 10 if (metadata != null) { 11 metadata.clear(pvs); 12 } 13 metadata = buildResourceMetadata(clazz); 14 this.injectionMetadataCache.put(cacheKey, metadata); 15 } 16 } 17 } 18 return metadata; 19 } 20 21 private InjectionMetadata buildResourceMetadata(final Class<?> clazz) { 22 if (!AnnotationUtils.isCandidateClass(clazz, resourceAnnotationTypes)) { 23 return InjectionMetadata.EMPTY; 24 } 25 26 List<InjectionMetadata.InjectedElement> elements = new ArrayList<>(); 27 Class<?> targetClass = clazz; 28 29 do { 30 final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>(); 31 32 ReflectionUtils.doWithLocalFields(targetClass, field -> { 33 if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) { 34 if (Modifier.isStatic(field.getModifiers())) { 35 throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields"); 36 } 37 currElements.add(new WebServiceRefElement(field, field, null)); 38 } 39 else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) { 40 if (Modifier.isStatic(field.getModifiers())) { 41 throw new IllegalStateException("@EJB annotation is not supported on static fields"); 42 } 43 currElements.add(new EjbRefElement(field, field, null)); 44 } 45 else if (field.isAnnotationPresent(Resource.class)) { 46 if (Modifier.isStatic(field.getModifiers())) { 47 throw new IllegalStateException("@Resource annotation is not supported on static fields"); 48 } 49 if (!this.ignoredResourceTypes.contains(field.getType().getName())) { 50 currElements.add(new ResourceElement(field, field, null)); 51 } 52 } 53 }); 54 55 ReflectionUtils.doWithLocalMethods(targetClass, method -> { 56 Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); 57 if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { 58 return; 59 } 60 if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { 61 if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) { 62 if (Modifier.isStatic(method.getModifiers())) { 63 throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods"); 64 } 65 if (method.getParameterCount() != 1) { 66 throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method); 67 } 68 PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); 69 currElements.add(new WebServiceRefElement(method, bridgedMethod, pd)); 70 } 71 else if (ejbRefClass != null && bridgedMethod.isAnnotationPresent(ejbRefClass)) { 72 if (Modifier.isStatic(method.getModifiers())) { 73 throw new IllegalStateException("@EJB annotation is not supported on static methods"); 74 } 75 if (method.getParameterCount() != 1) { 76 throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method); 77 } 78 PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); 79 currElements.add(new EjbRefElement(method, bridgedMethod, pd)); 80 } 81 else if (bridgedMethod.isAnnotationPresent(Resource.class)) { 82 if (Modifier.isStatic(method.getModifiers())) { 83 throw new IllegalStateException("@Resource annotation is not supported on static methods"); 84 } 85 Class<?>[] paramTypes = method.getParameterTypes(); 86 if (paramTypes.length != 1) { 87 throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method); 88 } 89 if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) { 90 PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); 91 currElements.add(new ResourceElement(method, bridgedMethod, pd)); 92 } 93 } 94 } 95 }); 96 97 elements.addAll(0, currElements); 98 targetClass = targetClass.getSuperclass(); 99 } 100 while (targetClass != null && targetClass != Object.class); 101 102 return InjectionMetadata.forElements(elements, clazz); 103 }
可以看到是利用反射遍歷字段和方法,獲取帶@Resource 注解的屬性和方法,然后創建ResourceElement 對象之后封裝成對象返回,最后獲取到的metadata 對象如下:
(2) org.springframework.beans.factory.annotation.InjectionMetadata#inject 方法進行注入
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Collection<InjectedElement> checkedElements = this.checkedElements; Collection<InjectedElement> elementsToIterate = (checkedElements != null ? checkedElements : this.injectedElements); if (!elementsToIterate.isEmpty()) { for (InjectedElement element : elementsToIterate) { if (logger.isTraceEnabled()) { logger.trace("Processing injected element of bean '" + beanName + "': " + element); } element.inject(target, beanName, pvs); } } } /** * Either this or {@link #getResourceToInject} needs to be overridden. */ protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable { if (this.isField) { Field field = (Field) this.member; ReflectionUtils.makeAccessible(field); field.set(target, getResourceToInject(target, requestingBeanName)); } else { if (checkPropertySkipping(pvs)) { return; } try { Method method = (Method) this.member; ReflectionUtils.makeAccessible(method); method.invoke(target, getResourceToInject(target, requestingBeanName)); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
可以看到是遍歷獲取到的element 集合,然后依次進行調用其 inject 方法。並且是采用模板方法模式,后面子類需要重寫inject 或者 getResourceToInject 方法。
(3) 走field.set(target, getResourceToInject(target, requestingBeanName)); 這里實際就是反射設置屬性的值,field 就是需要注入的對象,target 就是目標對象。值也就是需要注入的屬性的值調用到:org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.ResourceElement#getResourceToInject
@Override protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) { return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) : getResource(this, requestingBeanName)); }
繼續調用走org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#getResource:
protected Object getResource(LookupElement element, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException { if (StringUtils.hasLength(element.mappedName)) { return this.jndiFactory.getBean(element.mappedName, element.lookupType); } if (this.alwaysUseJndiLookup) { return this.jndiFactory.getBean(element.name, element.lookupType); } if (this.resourceFactory == null) { throw new NoSuchBeanDefinitionException(element.lookupType, "No resource factory configured - specify the 'resourceFactory' property"); } return autowireResource(this.resourceFactory, element, requestingBeanName); }
走最后的方法
(4) org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#autowireResource
/** * Obtain a resource object for the given name and type through autowiring * based on the given factory. * @param factory the factory to autowire against * @param element the descriptor for the annotated field/method * @param requestingBeanName the name of the requesting bean * @return the resource object (never {@code null}) * @throws NoSuchBeanDefinitionException if no corresponding target resource found */ protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName) throws NoSuchBeanDefinitionException { Object resource; Set<String> autowiredBeanNames; String name = element.name; if (factory instanceof AutowireCapableBeanFactory) { AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory; DependencyDescriptor descriptor = element.getDependencyDescriptor(); if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) { // 容器中沒有對應name的bean autowiredBeanNames = new LinkedHashSet<>(); resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null); if (resource == null) { throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object"); } } else { // 容器中有對應name的bean resource = beanFactory.resolveBeanByName(name, descriptor); autowiredBeanNames = Collections.singleton(name); } } else { resource = factory.getBean(name, element.lookupType); autowiredBeanNames = Collections.singleton(name); } if (factory instanceof ConfigurableBeanFactory) { ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory; for (String autowiredBeanName : autowiredBeanNames) { if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) { beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName); } } } return resource; }
這里可以看到先根據name 判斷容器是否有對應name的bean。然后走不同的解析方法獲取依賴的對象,然后返回去用於反射設置屬性。
- 對於存在name的bean調用鏈如下, 相當於從容器中直接調用getBean(name)獲取bean,比如上面依賴注入class3:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeanByName:
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { return getBean(name, descriptor.getDependencyType()); } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String, java.lang.Class<T>):
@Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); }
對應的beanName 和 requiredType 如下:
- 對於不存在name的bean調用鏈如下,比如上面依賴注入class33933, 如果解析不到bean 就拋出異常NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object")
org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency:
@Override @Nullable public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } }
相關的參數 descriptor 如下:
然后走代碼doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); 調用到:org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency

@Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); try { return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); } catch (UnsupportedOperationException ex) { // A custom TypeConverter which does not support TypeDescriptor resolution... return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
核心邏輯如下:
1》descriptor.getDependencyType(); 找到依賴的類型,如上會獲取到 class cn.qlq.dubbo.injecttest.Class3
2》org.springframework.beans.factory.support.DefaultListableBeanFactory#findAutowireCandidates 根據type 獲取到容器中存在的beanName

protected Map<String, Object> findAutowireCandidates( @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) { Class<?> autowiringType = classObjectEntry.getKey(); if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = classObjectEntry.getValue(); autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty()) { boolean multiple = indicatesMultipleBeans(requiredType); // Consider fallback matches if the first pass failed to find anything... DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) && (!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) { addCandidateEntry(result, candidate, descriptor, requiredType); } } if (result.isEmpty() && !multiple) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; }
candidateNames 獲取到的值是: ["class3"]
其實也是調用BeanFactory 的方法: org.springframework.beans.factory.BeanFactoryUtils#beanNamesForTypeIncludingAncestors(org.springframework.beans.factory.ListableBeanFactory, java.lang.Class<?>, boolean, boolean)
public static String[] beanNamesForTypeIncludingAncestors( ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { Assert.notNull(lbf, "ListableBeanFactory must not be null"); String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); if (lbf instanceof HierarchicalBeanFactory) { HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { String[] parentResult = beanNamesForTypeIncludingAncestors( (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); result = mergeNamesWithParent(result, parentResult, hbf); } } return result; }
lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); 根據類型獲取name
3》判斷獲取到的matchingBeans。
如果為空,返回null, 則上層拋出NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object")
如果不為空,獲取到autowiredBeanName, 然后直接從matchingBeans 獲取到一個valuue 然后返回去,也就是獲取到滿足條件的bean
2. @Autowired 注入過程
1. 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 屬性設置過程中,同上面代碼一樣有獲取InstantiationAwareBeanPostProcessor 后置處理器,然后調用postProcessProperties 方法的過程。其中@Autowired和@Value 使用的是org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex); } return pvs; } private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } metadata = buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } } } return metadata; } private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } metadata = buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } } } return metadata; } private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { 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<>(); 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)); } }); 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); }
可以看到第一步是調用findAutowiringMetadata 獲取到InjectionMetadata 對象,實際也就是遍歷該類的所有字段和相關方法,過濾帶有@Autowired和@Value 注解屬性的構造成InjectedElement 對象。
獲取到的對象如下:
2. 調用org.springframework.beans.factory.annotation.InjectionMetadata#inject
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Collection<InjectedElement> checkedElements = this.checkedElements; Collection<InjectedElement> elementsToIterate = (checkedElements != null ? checkedElements : this.injectedElements); if (!elementsToIterate.isEmpty()) { for (InjectedElement element : elementsToIterate) { if (logger.isTraceEnabled()) { logger.trace("Processing injected element of bean '" + beanName + "': " + element); } element.inject(target, beanName, pvs); } } }
遍歷上面獲取到的element 對象,然后調用其inject 方法,可以理解為一種策略模式的實現,調用不同實現類的inject 方法。
AutowiredFieldElement 和 AutowiredMethodElement 源碼如下:

private class AutowiredFieldElement extends InjectionMetadata.InjectedElement { private final boolean required; private volatile boolean cached = false; @Nullable private volatile Object cachedFieldValue; public AutowiredFieldElement(Field field, boolean required) { super(field, null); this.required = required; } @Override protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Field field = (Field) this.member; Object value; if (this.cached) { value = resolvedCachedArgument(beanName, this.cachedFieldValue); } else { DependencyDescriptor desc = new DependencyDescriptor(field, this.required); desc.setContainingClass(bean.getClass()); Set<String> autowiredBeanNames = new LinkedHashSet<>(1); Assert.state(beanFactory != null, "No BeanFactory available"); TypeConverter typeConverter = beanFactory.getTypeConverter(); try { value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } synchronized (this) { if (!this.cached) { if (value != null || this.required) { this.cachedFieldValue = desc; registerDependentBeans(beanName, autowiredBeanNames); if (autowiredBeanNames.size() == 1) { String autowiredBeanName = autowiredBeanNames.iterator().next(); if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { this.cachedFieldValue = new ShortcutDependencyDescriptor( desc, autowiredBeanName, field.getType()); } } } else { this.cachedFieldValue = null; } this.cached = true; } } } if (value != null) { ReflectionUtils.makeAccessible(field); field.set(bean, value); } } } /** * Class representing injection information about an annotated method. */ private class AutowiredMethodElement extends InjectionMetadata.InjectedElement { private final boolean required; private volatile boolean cached = false; @Nullable private volatile Object[] cachedMethodArguments; public AutowiredMethodElement(Method method, boolean required, @Nullable PropertyDescriptor pd) { super(method, pd); this.required = required; } @Override protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { if (checkPropertySkipping(pvs)) { return; } Method method = (Method) this.member; Object[] arguments; if (this.cached) { // Shortcut for avoiding synchronization... arguments = resolveCachedArguments(beanName); } else { int argumentCount = method.getParameterCount(); arguments = new Object[argumentCount]; DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount]; Set<String> autowiredBeans = new LinkedHashSet<>(argumentCount); Assert.state(beanFactory != null, "No BeanFactory available"); TypeConverter typeConverter = beanFactory.getTypeConverter(); for (int i = 0; i < arguments.length; i++) { MethodParameter methodParam = new MethodParameter(method, i); DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required); currDesc.setContainingClass(bean.getClass()); descriptors[i] = currDesc; try { Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter); if (arg == null && !this.required) { arguments = null; break; } arguments[i] = arg; } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex); } } synchronized (this) { if (!this.cached) { if (arguments != null) { DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, arguments.length); registerDependentBeans(beanName, autowiredBeans); if (autowiredBeans.size() == argumentCount) { Iterator<String> it = autowiredBeans.iterator(); Class<?>[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { String autowiredBeanName = it.next(); if (beanFactory.containsBean(autowiredBeanName) && beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) { cachedMethodArguments[i] = new ShortcutDependencyDescriptor( descriptors[i], autowiredBeanName, paramTypes[i]); } } } this.cachedMethodArguments = cachedMethodArguments; } else { this.cachedMethodArguments = null; } this.cached = true; } } } if (arguments != null) { try { ReflectionUtils.makeAccessible(method); method.invoke(bean, arguments); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } @Nullable private Object[] resolveCachedArguments(@Nullable String beanName) { Object[] cachedMethodArguments = this.cachedMethodArguments; if (cachedMethodArguments == null) { return null; } Object[] arguments = new Object[cachedMethodArguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = resolvedCachedArgument(beanName, cachedMethodArguments[i]); } return arguments; } }
3. 對於AutowiredFieldElement 對象的調用如下: (也就是前面三種屬性的注入,是走的AutowiredFieldElement.inject 方法,該方法內部的重要的是先獲取到依賴的bean,然后反射調用field.set(bean, value); 反射設置屬性為獲取到的bean)
(1) org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject 方法內部會調用org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency 進行注入,也就是上面的根據類型注入的過程:
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } }
相關實參如下:
(2) 上面方法走 doResolveDependency 調用到org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency, 傳遞的參數如下:

@Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); try { return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); } catch (UnsupportedOperationException ex) { // A custom TypeConverter which does not support TypeDescriptor resolution... return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
1》 Class<?> type = descriptor.getDependencyType(); 獲取到需要注入的bean的類型
2》Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); 根據descriptor 獲取注解上的value 屬性
3》value 如果是String 類型,也就是@Value 注入的屬性,走resolveEmbeddedValue((String) value) 獲取值,最終會調用到 org.springframework.core.env.PropertySourcesPropertyResolver#getPropertyAsRawString, 其實也就是從environment 環境中獲取配置信息, 然后轉換類型之后返回; 比如上面用@Value 注入Integer 類型的數據,實際就是先獲取到String 類型的數據,然后用Convert 進行轉換之后返回。
4》如果不是String類型,也就是@Autowired 注入的bean,走org.springframework.beans.factory.support.DefaultListableBeanFactory#findAutowireCandidates 獲取到相關的bean,獲取到之后進行返回
5》返回之后上層獲取到相關bean,然后用反射設置字段的值
4. 對於AutowiredMethodElement 方法的inject方法分析:方setter法自動注入
其實這個和上面一樣都是先org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency 獲取bean,只是后續操作不同
1》method.getParameterCount(); 獲取到參數個數
2》循環參數,然后調用org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency 這個獲取bean。獲取到之后加入到arguments 參數列表
3》走下面方法,反射調用方法進行setter 方法調用
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);
補充:關於Autowired 的自動注入的多個bean的解決辦法
1. Autowired 默認是根據類型進行查找,如果根據type 找到多個滿足條件的bean; 談話autowired 默認會根據屬性的名稱進行匹配(用屬性名稱作為beanName 判斷是否有名稱一致的)。如果有則返回beanName 與 屬性名稱一致的,如果沒有則報出異常
2. 也可以結合@Qualifier 注解限定名稱進行匹配
3. 也可以對注入的bean 用 @Primary 進行聲明,這樣根據類型進行獲取的時候只會獲取到一個。
測試如下以及源碼分析:
(1) 相關類:
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Class1 { @Autowired private Interface1 interface1; }
package cn.qlq.dubbo.injecttest; public interface Interface1 { } package cn.qlq.dubbo.injecttest; import org.springframework.stereotype.Component; @Component public class InterfaceImpl1 implements Interface1{ } package cn.qlq.dubbo.injecttest; import org.springframework.stereotype.Component; @Component public class InterfaceImpl2 implements Interface1{ }
(2) 如上類啟動會報錯:
Description: Field interface1 in cn.qlq.dubbo.injecttest.Class1 required a single bean, but 2 were found: - interfaceImpl1: defined in file [E:\xiangmu\springcloud\dubbo-service-consumer\target\classes\cn\qlq\dubbo\injecttest\InterfaceImpl1.class] - interfaceImpl2: defined in file [E:\xiangmu\springcloud\dubbo-service-consumer\target\classes\cn\qlq\dubbo\injecttest\InterfaceImpl2.class]
查看源碼
1》org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject 自動注入過程
2》上面調用org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency 獲取依賴的bean
3》上面調用org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency:
@Nullable public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } Class<?> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); try { return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); } catch (UnsupportedOperationException ex) { // A custom TypeConverter which does not support TypeDescriptor resolution... return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
這里獲取到的matchingBeans 如下:
然后size > 1, 會調用org.springframework.beans.factory.support.DefaultListableBeanFactory#determineAutowireCandidate 根據DependencyDescriptor 獲取比較匹配的beanName:
protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) { Class<?> requiredType = descriptor.getDependencyType(); String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { return primaryCandidate; } String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return priorityCandidate; } // Fallback for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateName = entry.getKey(); Object beanInstance = entry.getValue(); if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) || matchesBeanName(candidateName, descriptor.getDependencyName())) { return candidateName; } } return null; }
可以看到這個方法里面簡單的處理邏輯:第一步獲取primary 聲明的beanname; 如果沒有獲取到就用org.springframework.beans.factory.support.DefaultListableBeanFactory#matchesBeanName 方法找到匹配的beanname(也就是找到beanName或者bean的別名等於descriptor.getDependencyName() 的beanName)
如果上面找到了滿足條件的一個beanName 就獲取到bean 后返回,否則會報出上面的異常。
(3) 解決辦法:
1》修改屬性名稱,屬性名稱也就是descriptor.getDependencyName()
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Class1 { @Autowired private Interface1 interfaceImpl2; }
解釋:
這時候會獲取到的最匹配的beanName如下:(也就是屬性名稱作為beanName去匹配能找到匹配的beanName)
2》加@Qualifier 進行限定
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class Class1 { @Autowired @Qualifier("interfaceImpl2") private Interface1 interface1; }
源碼解釋:
加了@Qualifier 之后Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); 會根據指定的beanName 進行獲取,其調用鏈如下:
最終返回的就是@Qualifier 聲明的beanName 以及 bean:
3》實現類加@Primary 進行聲明
package cn.qlq.dubbo.injecttest; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component @Primary public class InterfaceImpl2 implements Interface1{ }
源碼解釋:
加了@Primary 注解,matchingBeans 返回的仍然是2個,只是determineAutowireCandidate 會先找primary 屬性的bean
4》修改具體實現類注入到spring的beanName 和 屬性名稱,這個解決方案同1》
可以看到這個解決方案與自動注入的類型無關,屬於對象工廠BeanFactory的一套機制。所以上面@Resource 自動注入過程調用此方法也是這樣的邏輯。
總結:
0. 自動注入的模式有下面五種:
// 不進行自動注入 int AUTOWIRE_NO = 0; // 根據name去容器找 int AUTOWIRE_BY_NAME = 1; // 根據類型去容器找 int AUTOWIRE_BY_TYPE = 2; // 從構造函數進行注入 int AUTOWIRE_CONSTRUCTOR = 3; /** @deprecated */ // 自動發現 @Deprecated int AUTOWIRE_AUTODETECT = 4;
這里的自動注入說的是Spring 自動注入帶setter 方法的屬性,和@Autowired、@Resource 注解無關。 是說在屬性注入 populateBean 方法中如何處理那些setter 方法掃描出來的bean, 默認是不進行注入。
1. Spring 自動注入的方式有: 構造注入、屬性注入、setter 注入, 其注入過程也都在上面分析了。
(1) 構造注入的過程是用策略模式解析到需要注入的bean,然后反射創建構造函數。
(2)屬性注入和方法注入是在IOC過程中的org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 方法
注入是在org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties 中開始注入過程,也是后置處理器的使用屬性過程中。 @Resource 與@Autowired 注入分別發生在CommonAnnotationBeanPostProcessor 和 AutowiredAnnotationBeanPostProcessor, @Value 也發生在AutowiredAnnotationBeanPostProcessor
2. @Autowired 自動注入的過程如下:
(1)解析屬性和方法中帶@Autowired或者@Value 屬性的,構造成Element 對象集合;
(2)遍歷集合調用AutowiredFieldElement、AutowiredMethodElement 的inject 方法
(3)方法內部的核心操作是獲取bean,然后反射設置屬性或者調用方法
獲取屬性調用的是org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency。核心過程如下:
1》先根據類型獲取到滿足條件的bean,返回的bean存在Map<String, Object> matchingBeans 容器中
2》判斷上面的matchingBeans 是否有元素
集合為空,報NoSuchBeanDefinitionException 異常
集合大小為1,返回找到的bean
集合大小大於1, 則有一套匹配beanName的規則:先獲取primary聲明的對象;找不到primary 聲明的對象就根據屬性name 和 當前的beanName進行匹配,滿足則返回,不滿足則報異常NoUniqueBeanDefinitionException。
3. Spring 中@Resource 發生注入的過程如下:
1》 注解上沒帶name 屬性,會默認以屬性名稱作為beanName 去 容器中獲取對象,如果獲取到則直接返回;獲取不到,也就是容器中不存在和屬性名一致的bean,則走上面org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency 的規則,同@Autowired 后續一樣。
2》注解上帶name 屬性,直接根據name 屬性獲取,獲取不到則報錯。
4. 也可以向BeanDefinition內部維護的propertyValues 緩存中添加相關屬性
5. 總結就是:
@Autowired 先根據類型獲取,獲取到1個則直接注入;獲取到多個再根據primary或者屬性的名稱與beanName 進行匹配。
@Resource 默認先根據屬性名稱獲取,也就是先byName;然后byType,同上面@Autowired 機制一樣。
補充:自動注入也可以注入數組、集合、Map ,注入的時候如果容器中沒有相關對象會找默認的
1. 源碼查看
自動注入相關屬性:在掃描到自動注入注解之后會調用到 org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveMultipleBeans
@Nullable private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { final Class<?> type = descriptor.getDependencyType(); if (descriptor instanceof StreamDependencyDescriptor) { Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } Stream<Object> stream = matchingBeans.keySet().stream() .map(name -> descriptor.resolveCandidate(name, type, this)) .filter(bean -> !(bean instanceof NullBean)); if (((StreamDependencyDescriptor) descriptor).isOrdered()) { stream = stream.sorted(adaptOrderComparator(matchingBeans)); } return stream; } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); ResolvableType resolvableType = descriptor.getResolvableType(); Class<?> resolvedArrayType = resolvableType.resolve(type); if (resolvedArrayType != type) { componentType = resolvableType.getComponentType().resolve(); } if (componentType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType); if (result instanceof Object[]) { Comparator<Object> comparator = adaptDependencyComparator(matchingBeans); if (comparator != null) { Arrays.sort((Object[]) result, comparator); } } return result; } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric(); if (elementType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (result instanceof List) { Comparator<Object> comparator = adaptDependencyComparator(matchingBeans); if (comparator != null) { ((List<?>) result).sort(comparator); } } return result; } else if (Map.class == type) { ResolvableType mapType = descriptor.getResolvableType().asMap(); Class<?> keyType = mapType.resolveGeneric(0); if (String.class != keyType) { return null; } Class<?> valueType = mapType.resolveGeneric(1); if (valueType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { return null; } }
可以看到處理相關的集合數組和map。
2. 測試
接口:
package cn.qlq.dubbo.injecttest; public interface Interface1 { }
實現類1:
package cn.qlq.dubbo.injecttest; import org.springframework.stereotype.Component; @Component("myImpl1") public class InterfaceImpl1 implements Interface1 { }
實現類2:
package cn.qlq.dubbo.injecttest; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component @Primary public class InterfaceImpl2 implements Interface1 { }
測試類:
package cn.qlq.dubbo.injecttest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; import java.util.Map; @Component public class Class1 { @Autowired public void setList(List<Interface1> interface1s) { System.out.println("******"); interface1s.forEach(System.out::println); System.out.println("******"); } @Autowired public void setArray(Interface1[] interface1s) { System.out.println("000000"); Arrays.stream(interface1s).forEach(System.out::println); System.out.println("000000"); } @Autowired public void setMap(Map<String, Interface1> map) { System.out.println("111111"); map.forEach((k, v) -> { System.out.println(k + "\t" + v); }); System.out.println("111111"); } }
結果:
000000 cn.qlq.dubbo.injecttest.InterfaceImpl1@5e99b9c cn.qlq.dubbo.injecttest.InterfaceImpl2@2fe74516 000000 111111 myImpl1 cn.qlq.dubbo.injecttest.InterfaceImpl1@5e99b9c interfaceImpl2 cn.qlq.dubbo.injecttest.InterfaceImpl2@2fe74516 111111 ****** cn.qlq.dubbo.injecttest.InterfaceImpl1@5e99b9c cn.qlq.dubbo.injecttest.InterfaceImpl2@2fe74516 ******
補充:關於lazy 解決循環依賴的思路
lazy 可以解決循環依賴的錯誤,其原理是在獲取依賴注入過程中,代碼走如下代碼:
org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency:
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(this.getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return this.createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class != descriptor.getDependencyType() && ObjectProvider.class != descriptor.getDependencyType()) { if (javaxInjectProviderClass == descriptor.getDependencyType()) { return (new DefaultListableBeanFactory.Jsr330Factory()).createDependencyProvider(descriptor, requestingBeanName); } else { Object result = this.getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName); if (result == null) { result = this.doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } else { return new DefaultListableBeanFactory.DependencyObjectProvider(descriptor, requestingBeanName); } }
代碼會走 getLazyResolutionProxyIfNecessary 獲取lazy 修飾的代理對象,如果返回Wienull就從容器找對象。
調用到: org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver#getLazyResolutionProxyIfNecessary 拿lazy 修飾的代理對象
public Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, @Nullable String beanName) { return (isLazy(descriptor) ? buildLazyResolutionProxy(descriptor, beanName) : null); } protected boolean isLazy(DependencyDescriptor descriptor) { for (Annotation ann : descriptor.getAnnotations()) { Lazy lazy = AnnotationUtils.getAnnotation(ann, Lazy.class); if (lazy != null && lazy.value()) { return true; } } MethodParameter methodParam = descriptor.getMethodParameter(); if (methodParam != null) { Method method = methodParam.getMethod(); if (method == null || void.class == method.getReturnType()) { Lazy lazy = AnnotationUtils.getAnnotation(methodParam.getAnnotatedElement(), Lazy.class); if (lazy != null && lazy.value()) { return true; } } } return false; } protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final @Nullable String beanName) { BeanFactory beanFactory = getBeanFactory(); Assert.state(beanFactory instanceof DefaultListableBeanFactory, "BeanFactory needs to be a DefaultListableBeanFactory"); final DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; TargetSource ts = new TargetSource() { @Override public Class<?> getTargetClass() { return descriptor.getDependencyType(); } @Override public boolean isStatic() { return false; } @Override public Object getTarget() { Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<>(1) : null); Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null); if (target == null) { Class<?> type = getTargetClass(); if (Map.class == type) { return Collections.emptyMap(); } else if (List.class == type) { return Collections.emptyList(); } else if (Set.class == type || Collection.class == type) { return Collections.emptySet(); } throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(), "Optional dependency not present for lazy injection point"); } if (autowiredBeanNames != null) { for (String autowiredBeanName : autowiredBeanNames) { if (dlbf.containsBean(autowiredBeanName)) { dlbf.registerDependentBean(autowiredBeanName, beanName); } } } return target; } @Override public void releaseTarget(Object target) { } }; ProxyFactory pf = new ProxyFactory(); pf.setTargetSource(ts); Class<?> dependencyType = descriptor.getDependencyType(); if (dependencyType.isInterface()) { pf.addInterface(dependencyType); } return pf.getProxy(dlbf.getBeanClassLoader()); }
可以看到會判斷是否有注解Lazy, 如果有相關注解的話先返回一個代理對象。