Spring IOC(六)AutowiredAnnotationBeanPostProcessor 原理分析

使用Spring 编程时,使用Ioc,我们只需要声明对象,而由Spring 替我门自动注入,而其中起重要作用则为 AutowiredAnnotationBeanPostProcessor,它在bean实例化后,进行这重要的初始化操作。

AutowiredAnnotationBeanPostProcessor

支持 @Autowired@Value 注解的支持也支持 @Inject 注解,也可以给setter 方法进行注入。也包括对 @Lookup 注解解析。

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
		... 
		}

AutowiredAnnotationBeanPostProcessor 实现了多个接口及抽象类,重要的为 InstantiationAwareBeanPostProcessorAdapterMergedBeanDefinitionPostProcessor等,而 InstantiationAwareBeanPostProcessorAdapter 则为 SmartInstantiationAwareBeanPostProcessor 类型。

初始化地方

AutowiredAnnotationBeanPostProcessor 是在 AnnotationConfigApplicationContext 初始化时就被加入到 BeanFactory 中,所以所有bean被加载时候,都会执行这个 PostProcessor

在初始化 AnnotationConfigApplicationContext 时候,会网beanDefs中加入一些默认配置bean:

  • org.springframework.context.annotation.internalConfigurationAnnotationProcessor:对应 ConfigurationClassPostProcessor
  • org.springframework.context.annotation.internalAutowiredAnnotationProcessor 对应 AutowiredAnnotationBeanPostProcessor
  • org.springframework.context.annotation.internalCommonAnnotationProcessor" 对应 CommonAnnotationBeanPostProcessor
  • org.springframework.context.annotation.internalPersistenceAnnotationProcessor 对应 org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
  • org.springframework.context.event.internalEventListenerProcessor 对应 EventListenerMethodProcessor
  • org.springframework.context.event.internalEventListenerFactory 对应 DefaultEventListenerFactory

determineCandidateConstructors

首先从实例化开始,对上一篇中 getBeancreateBeanInstance 进行进一步分析,当一个bean的构造方法为多个参数,且 参数有用 @Autowired 时候,则需要判断参数是否需要 autowired

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		... 
		// 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);
		}
		.. 
	}

而 具体则利用 postProcessor 去分析:

	@Nullable
	protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
			throws BeansException {

		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
		// 判断是否有初始化前后调用的postprocessors
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					// 执行所有的 SmartInstantiationAwareBeanPostProcessor
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
					if (ctors != null) {
					// 找到第一个不为空的则返回
						return ctors;
					}
				}
			}
		}
		return null;
	}

接下来看重点方法: AutowiredAnnotationBeanPostProcessordetermineCandidateConstructors

@Override
	@Nullable
	public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
			throws BeanCreationException {

		// 检查是否有 lookup,如果没有则进入
		if (!this.lookupMethodsChecked.contains(beanName)) {
			try {
			// 对所有 方法执行 lambd逻辑
				ReflectionUtils.doWithMethods(beanClass, method -> {
				// 看是否 有lookUp逻辑
					Lookup lookup = method.getAnnotation(Lookup.class);
					if (lookup != null) {
					// 如果最终有 @Lookup修饰
						Assert.state(this.beanFactory != null, "No BeanFactory available");
						LookupOverride override = new LookupOverride(method, lookup.value());
						try {
						// 将override方法注册进 BeanDefinition
							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);
			}
			// 并将它加入到 lookupMethodsChecked 中
			this.lookupMethodsChecked.add(beanName);
		}

		// 首先从缓存中拿,看是否能拿到
		Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
		if (candidateConstructors == null) {
			// 完全加锁
			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,其他类则只返回null
					Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
					int nonSyntheticConstructors = 0;
					for (Constructor<?> candidate : rawCandidates) {
						if (!candidate.isSynthetic()) {
						// 如果不是 synthetic,则自增
							nonSyntheticConstructors++;
						}
						else if (primaryConstructor != null) {
							continue;
						}
						// 从该 构造方法中,获取注解信息
						AnnotationAttributes ann = findAutowiredAnnotation(candidate);
						if (ann == null) {
						// 如果自身没有使用 @Autowired或者 @Value修饰的,则看其父类是否有。
							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...
								}
							}
						}
						if (ann != null) {
						// 如果自己没有需要@Autowried的,但是父类有,那么一场了。
							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;
							}
							// 只有当需要@Autowired 则需要加入到候选中
							candidates.add(candidate);
						}
						else if (candidate.getParameterCount() == 0) {
						// 如果参数个数为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]);
					}
					else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
						candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
					}
					else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
							defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
						candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
					}
					else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
						candidateConstructors = new Constructor<?>[] {primaryConstructor};
					}
					else {
					// 如果是无参构造方法,默认则为空数组
						candidateConstructors = new Constructor<?>[0];
					}
					// 将候选构造方法,都放入 candidateConstructorsCache 中。
					this.candidateConstructorsCache.put(beanClass, candidateConstructors);
				}
			}
		}
		// 返回构造方法
		return (candidateConstructors.length > 0 ? candidateConstructors : null);
	}
  1. 再一次检查所有方法是否包含 @Lookup 注解,有就放入 lookupMethodsChecked 中 。
  2. 检查构造方法,并且看构造方法中,是否有 @Autowired@Value 修饰。如果有则会加入到 candidateConstructorsCache 中。

findAutowiredAnnotation 即为获取所有参数,看是否有 用 @Autowired@Value 修饰参数:

	private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
		if (ao.getAnnotations().length > 0) {  // autowiring annotations have to be local
		// 此时 autowiredAnnotationTypes 只有两个字段,@Autowired 和 @Value
			for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
				AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
				if (attributes != null) {
					return attributes;
				}
			}
		}
		return null;
	}
  1. 如果是无参构造方法,则会返回null,有参则会返回所有构造方法。

autowireConstructor

从上面获取构造方法,如果有 多参构造方法,且有 需要 @Autowried 的, 则会进入 AbstractAutowireCapableBeanFactory

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		// 有多参构造方法,且有@Autowired 方法注释
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

autowireConstructor:

	protected BeanWrapper autowireConstructor(
			String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {

		return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
	}

postProcessMergedBeanDefinition

这是主要注入方法,在 上面获取完构造方法后,则会进行实例化,而实例化完之后,Spring 同样提供了 模块从而可以进行对bean实例化后的初始化操作,具体调用点在 doCreateBean -> applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

这样依赖,所有 MergedBeanDefinitionPostProcessor均可以执行,从而会到 AutowiredAnnotationBeanPostProcessor中的 postProcessMergedBeanDefinition

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}
  1. findAutowiringMetadata:获取 所 有 @Autowired@Value 数据,而后封装 放入 injectionMetadataCache 中。实际主题方法则是在 buildAutowiringMetadata 中进行。
	private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
		// 获取缓存key
		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
		// 首先从缓存中获取。
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
		if (InjectionMetadata.needsRefresh(metadata, clazz)) {
		// metadata==null或者clazz和 当前类不一致,则会进来
			synchronized (this.injectionMetadataCache) {
			// 再尝试获取一次
				metadata = this.injectionMetadataCache.get(cacheKey);
				// 在检查一次
				if (InjectionMetadata.needsRefresh(metadata, clazz)) {
					if (metadata != null) {
						metadata.clear(pvs);
					}
					// 构建Autowiring数据
					metadata = buildAutowiringMetadata(clazz);
					// 存入缓存,即beanName, reference
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}
  1. buildAutowiringMetadata :搜寻所有 非静态且有 @Autowired@Value 注解的方法和字段。
	private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
		// 对所有的字段进行处理
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
			// 获取该字段上面的@Autowired和 @Value注解
				AnnotationAttributes 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;
					}
					// 判断注解上require类型
					boolean required = determineRequiredStatus(ann);
					// 将其加入到 currElements中
					currElements.add(new AutowiredFieldElement(field, required));
				}
			});
			// 对所有方法进行注入
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				// 如果方法不可见,则返回
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				// 获取方法注解
				AnnotationAttributes 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 中。
					currElements.add(new AutowiredMethodElement(method, required, pd));
				}
			});
			// 
			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		// 往上寻找
		while (targetClass != null && targetClass != Object.class);
		// 构造InjectionMetadata返回
		return new InjectionMetadata(clazz, elements);
	}

很明显,Spring不支持静态方法和类的注入,但是却可以通过别的方法进行注入,例如:

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

或者使用 @PostConstruct 进行注入。

@Component
public class TestClass {
   private static AutowiredTypeComponent component;

   @Autowired
   private AutowiredTypeComponent autowiredComponent;

   @PostConstruct
   private void init() {
      component = this.autowiredComponent;
   }

   public static void testMethod() {
      component.callTestMethod();
   }
}

但是,并不推荐这样做,因为一个实例一旦是 static类型,那么它就脱离了Spring 容器管辖,它属于整个类了。

postProcessMergedBeanDefinition 中 第一行已分析完,主要功能就是获取所有 @Autowired \ @Value 的类和方法。下面看 checkConfigMembers 方法:

	public void checkConfigMembers(RootBeanDefinition beanDefinition) {
		Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
		// injectedElements 则为上一步中获取的所有待注入的字段和方法
		for (InjectedElement element : this.injectedElements) {
			Member member = element.getMember();
			// 如果该字段没有交由Spring 管理。
			if (!beanDefinition.isExternallyManagedConfigMember(member)) {
				beanDefinition.registerExternallyManagedConfigMember(member);
				// 将其加入到 checkedElements 中
				checkedElements.add(element);
				if (logger.isTraceEnabled()) {
					logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
				}
			}
		}
		this.checkedElements = checkedElements;
	}

checkConfigMembers 重点在于对上一步中找到的所有 待注入的方法,并将其加入到 beanDefinition中externallyManagedConfigMemberscheckedElements中。

整个 postProcessMergedBeanDefinition 并没有对内部静态变量进行赋值,而仅仅找出所有的 待注入类,存入了AutowiredAnnotationBeanPostProcessor 中。

postProcessProperties

整个实际的注入过程,则是在 postProcessProperties 中。而目前 外部调用处则只有 doCreateBean中的 popularBean 方法。

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		// 找到所有注入数据。popularBean 中 在前一步已经缓存了,具体调用为 postProcessMergedBeanDefinition 方法
		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;
	}
  1. 找到所有注入数据。popularBean 中 在前一步已经缓存了,具体调用为 postProcessMergedBeanDefinition 方法
  2. 具体注入逻辑 则在 metadata.inject(bean, beanName, pvs);
	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);
			}
		}
	}

上面获取到每个元素(InjectedElement)后,则执行其自身 inject 方法,而 pvs则为传入参数,可配置键值对。
InjectedElementInjectionMetadata 内部类,代表着待注入的元素,而 InjectedElement 实现类有
在这里插入图片描述
前两种则代表着注入方法和注入字段,后面几种则以后慢慢分析。

		@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
		// 获取当前field
			Field field = (Field) this.member;
			Object value;
			if (this.cached) {
				value = resolvedCachedArgument(beanName, this.cachedFieldValue);
			}
			else {
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
				// 设置 beanClass
				desc.setContainingClass(bean.getClass());
				// 用来存储候选的类 
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available");
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				try {
				// 主题获取方法,从beanFactory中获取对应 DependencyDescriptor 所需beanInstance
					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;
							// 在 beanFactory中注册 register bean。
							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);
			}
		}
	}
  1. 获取当前 InjectedElement 锁需要注入的bean类型 DependencyDescriptor
  2. 调用 beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter) 获取对应 依赖的 bean名称
    根据不同类型的注解进行处理。
  3. 将获取到的bean 实例,注入到 beanFactory的 dependentBeans中。
  4. 将 获取的 bean 实例,放入 cachedFieldValue 中缓存。
  5. 最后调用反射,给该字段设值。
	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
		// 设置 parameterNameDiscoverer
		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
		if (Optional.class == descriptor.getDependencyType()) {
		// 如果是 Optional类型的
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		// ObjectFactory 类型
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
		// 使用@Inject注解的
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
		// 首先判断是否有@Lazy注解
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
			// 普通获取。
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}
  1. 如果是@Lazy 注解的注入,则返回的不是具体实例,而是一个代理对象,而当调用具体方法时返回。
  2. 如果是普通的@Autowired注解 ,则主流程在 doResolveDependency 中进行,期间包括了对 @Qualifier@Primary 解析。
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();
			// 获取建议的值,即在 注解 @Value值中设置的值。
			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()));
				}
			}
			// 获取集合 bean的操作,包含array,Collection,Map等
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}
			// 获取其他bean的过程,例如多实例数据库的操作。这里有使用 @Qualifier 过滤,即如果使用 @Qualifier ,则会优先处理。
			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) {
			// 决定使用哪一个,判断 用到@Primary诸侯选
				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;
					}
				}
				// 直接获取选择出的autowiredBeanName
				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);
		}
	}

上面 doResolveDependency 则包括了主体流程,包括对 @Qualifier@Primary 解析等。

总结

整个 AutowiredAnnotationBeanPostProcessor 作用也好理解,它有以下作用:

  1. determineCandidateConstructors 负责找出具体构造方法,并且判断构造方法是否需要 @Autowired,而如果有需要构造方法@Autowired,则需要走另一种逻辑,这个可以看后面的循环依赖解决。
  2. postProcessProperties 对所有字段和方法,进行具体注入地方。
  3. postProcessMergedBeanDefinition 处理所有使用 @Autowired@Value 注解方法。

觉得博主写的有用,不妨关注博主公众号: 六点A君。
哈哈哈,一起研究Spring:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章