@Test
public void registerAndRefresh() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AutowiredConfig.class);
context.refresh();
context.getBean("testBean");
context.getBean("name");
Map<String, Object> beans = context.getBeansWithAnnotation(Configuration.class);
assertEquals(2, beans.size());
}
@Configuration
@Import(NameConfig.class)
static class AutowiredConfig {
@Autowired
private String name;
@Autowired
@Qualifier("testBean2")
private TestBean testBean;
}
@Configuration
static class NameConfig {
@Bean String name() { return "foo"; }
@Bean TestBean testBean() {
TestBean testBean = new TestBean();
return testBean;
}
@Bean TestBean testBean2() {
TestBean testBean = new TestBean();
return testBean;
}
}
class TestBean {
String name;
}
@Autowired 注解注入 bean 的逻辑主要是通过 AutowiredAnnotationBeanPostProcessor bean-post-processor 所实现的,那么涉及到三个问题,什么时候注册到ApplicationContext,什么时候被实例化,什么时候调用,怎么调用。这就是本篇文章需要分析的。
这部分在ApplicationContext容器初始化时注册,详见注册inner-bean-post-processor definitions的AnnotationConfigUtils#registerAnnotationConfigProcessors
这部分分为两个部分,首先实例化bean-post-processor,然后在将bean-post-processor实例注册到beanFactory中以备调用。详见
registerBeanPostProcessors
这一部分将详细解释@Autowired注解怎样将对象注入另一个对象中
首先看一下类图
可以看出AutowiredAnnotationBeanPostProcessor
实现了两个processor的接口。
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
default void resetBeanDefinition(String beanName) {
}
}
public abstract class InstantiationAwareBeanPostProcessorAdapter implements SmartInstantiationAwareBeanPostProcessor {
@Override
@Nullable
public Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@Override
@Nullable
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@Override
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
@Nullable
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return null;
}
@Deprecated
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
AutowiredAnnotationBeanPostProcessor
其实只实现了一个接口postProcessProperties
。
接下来具体分析AutowiredAnnotationBeanPostProcessor做了什么
AbstractAutowireCapableBeanFactory#doCreateBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
.....
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
....
}
AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
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);
}
}
}
可见,从Spring容器中取出已实例化的所有bean-post-processor,实例化过程参考注册inner-bean-post-processor definitions和实例化inner-bean-post-processor。然后依次调用postProcessMergedBeanDefinition。
AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
可见,通过调用 findAutowiringMetadata 方法返回一个 InjectionMetadata 类型的 metadata。
AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata
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.
//从容器中查找是否有给定类的autowire相关注解元信息
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) {
//clear metadata
metadata.clear(pvs);
}
//解析给定类autowire相关注解元信息
metadata = buildAutowiringMetadata(clazz);
//将得到的给定类autowire相关注解元信息存储在容器缓存中
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
其中最关注的就是buildAutowiringMetadata。这个方法构建了需要进行注入的bean集合。
AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata
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 -> {
//获取给定字段上的注解
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
//如果给定字段是静态的(Static),则直接遍历下一个字段
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
//判断注解的required属性值是否有效
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;
}
//获取给定方法上的所有注解
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);
}
}
//判断注解的required属性值是否有效
boolean required = determineRequiredStatus(ann);
//获取当前方法的属性描述符,即方法是可读的(readable)getter方法,
//还是可写的(writeable)setter方法
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
//将方法元信息封装添加到返回的元信息集合中
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
//将当前类的注解元信息存放到注解元信息集合中
elements.addAll(0, currElements);
//获取给定类的父类
targetClass = targetClass.getSuperclass();
}
//如果给定类有基类,并且基类不是Object,则递归获取其基类的元信息
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
这个方法分为两部分:
AbstractAutowireCapableBeanFactory#populateBean
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
和刚刚的一样,循环调用postProcessProperties方法
AutowiredAnnotationBeanPostProcessor#postProcessProperties
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
//获取指定类中autowire相关注解的元信息
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
//对Bean的属性进行自动注入
metadata.inject(bean, beanName, pvs);
return pvs;
}
这时的findAutowiringMetadata只需从缓存中取出metadata即可,因为在MergedBeanDefinitionPostProcessor步骤中已经解析完成。所以重点看下metadata.inject(bean, beanName, pvs)
方法
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);
}
}
}
如果checkedElements不为空,则执行element.inject(target, beanName, pvs)
方法。这里要声明一点InjectionMetadata对象本身是一个包含了一系列AutowiredFieldElement和AutowiredMethodElement对象的队列所构成。
所以要分来两部分说明。
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
Field field = (Field) this.member; // the @Autowired annotated field,
Object value;
if (this.cached) {
// 如果该 @Autowired ref bean 已经被解析过,直接从缓存中获取;
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// 1. 根据容器中Bean定义,解析指定的依赖关系,获取依赖对象
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
....
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value); // 2. 通过反射将 @Autowired annotated ref-bean 写入当前 bean 的属性中;
}
}
}
其实重点就是做了两件事情:首先,解析 @Autowired 所标注的 bean,获取当前要注入的bean的实例,然后,将该实例通过 field 注入当前的 bean
AutowiredMethodElement#inject
该方法与 #1 非常类似
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 {
// 返回该 lazy proxy 表示延迟初始化,实现过程是查看在 @Autowired 注解处是否使用了 @Lazy = true 注解
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// 大部分的通过 @Autowired 注解的普通 bean 将会在这里进行初始化
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
这里的解析根据@Autowired 的bean类型,分了四种情况进行处理
这里只针对普通的bean做分析
DefaultListableBeanFactory#doResolveDependency
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
...
Class<?> type = descriptor.getDependencyType();
...
//1. 根据 type 去找到对应的 candidates,该方法内部会处理 @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) {
//2. 根据 @Primary and @Priority 注解进行筛选
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(); // 这里返回的是 Class Type
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
if (instanceCandidate instanceof Class) {
// 3. 这里会调用 Factory.getBean.. 去实例化找到的 Class Type..
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);
}
}
这段代码主要做了三件事:
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
//根据candidate type从缓存中获取到bean name集合
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
// 1. 依次从所有已经解析的 Type 去找是否已经存在对应的 Type。如果有,则添加对应 Type 的 bean 实例到 result 队里当中;
// 注意,如果找到了,这里加入 result 的就不再是 Class Type 了,而是 instance
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) {
// 2. isAutowireCandidate(candidate, descriptor) 会去判断 @Qualifier 逻辑
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
// 根据 candidate 的名字找到其对应的 Type,返回并添加入 result, 比如得到 niba = class org.ss.spring.container.Test
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
...
return result;
}
而候选bean有两个,name分别为testBean和testBean2,这里需要解释的一点是,因为NameConfig
是通过@Import加载的,即在加载完Spring内置的bean之后会首先加载AutowiredConfig
,然后在加载NameConfig
,所以这里已解析的bean只有Spring内置bean
而这段代码主要做了两件事情,
从缓存中找该 requiredType 是否已经被成功解析过,若是,则直接返回缓存中已经解析好的实例;
注意,这里是该方法比较特殊的地方,它通过返回类型 Object 既可以返回 candidate Class Type,也可以返回 candidate instance。
若在缓存中没有找到,它会依次从当前的 candidates ( 这里的是 testBean和testBean2 )中去查找是否是最终符合的 candidate,如果是符合的 candidate,将会加入 result。
接下来进一步分析查找过程。
DefaultListableBeanFactory.java
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
throws NoSuchBeanDefinitionException {
String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
if (containsBeanDefinition(beanDefinitionName)) {
// 该方法的内部流程中会去判断 @Qualifier 逻辑
return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver);
}
else if (containsSingleton(beanName)) {
return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
}
// 如果在当前的 BeanFactory 中没有找到,将会继续从 Parent BeanFactory 中查找;
BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory) {
// No bean definition found in this factory -> delegate to parent.
return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
}
else if (parent instanceof ConfigurableListableBeanFactory) {
// If no DefaultListableBeanFactory, can't pass the resolver along.
return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
}
else {
return true;
}
}
该方法主要包含两部分逻辑,
下面就#1的isAutowireCandidate方法继续分析
DefaultListableBeanFactory.java
protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {
String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName);
// 解析 bean name 对应的 ClassType,并且将解析后的 ClassType 缓存到 bean definitions 中;
resolveBeanClass(mbd, beanDefinitionName);
if (mbd.isFactoryMethodUnique && mbd.factoryMethodToIntrospect == null) {
new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
}
return resolver.isAutowireCandidate(
new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor);
}
QualifierAnnotationAutowireCandidateResolver#isAutowireCandidate
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
boolean match = super.isAutowireCandidate(bdHolder, descriptor);
if (match) {
// 1. 在这里判断的 Qualifier;如果当前的 descriptor 中有标注 @Qualifier,那么 bean 必须与之匹配,才可以返回;
match = checkQualifiers(bdHolder, descriptor.getAnnotations());
if (match) {
// 2. 继续匹配 method 参数..
MethodParameter methodParam = descriptor.getMethodParameter();
if (methodParam != null) {
Method method = methodParam.getMethod();
if (method == null || void.class == method.getReturnType()) {
match = checkQualifiers(bdHolder, methodParam.getMethodAnnotations());
}
}
}
}
return match;
}
这里分别对属性和方法进行了匹配,首先对属性进行匹配,然后对方法进行匹配.
这里重点分析第一种情况。
QualifierAnnotationAutowireCandidateResolver#checkQualifiers
protected boolean checkQualifiers(BeanDefinitionHolder bdHolder, Annotation[] annotationsToSearch) {
if (ObjectUtils.isEmpty(annotationsToSearch)) {
return true;
}
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
for (Annotation annotation : annotationsToSearch) {
Class<? extends Annotation> type = annotation.annotationType();
boolean checkMeta = true;
boolean fallbackToMeta = false;
if (isQualifier(type)) {// 判断当前的注解是不是 @Qualifier
//1. 深度的根据 @Qualifier 中定义的 name 与当前 ref-bean 进行匹配 ..
if (!checkQualifier(bdHolder, annotation, typeConverter)) {
fallbackToMeta = true;
}
else {
checkMeta = false;
}
}
// 2. 从 meta annoation 中查找;
if (checkMeta) {
boolean foundMeta = false;
for (Annotation metaAnn : type.getAnnotations()) {
Class<? extends Annotation> metaType = metaAnn.annotationType();
if (isQualifier(metaType)) {
foundMeta = true;
// Only accept fallback match if @Qualifier annotation has a value...
// Otherwise it is just a marker for a custom qualifier annotation.
if ((fallbackToMeta && StringUtils.isEmpty(AnnotationUtils.getValue(metaAnn))) ||
!checkQualifier(bdHolder, metaAnn, typeConverter)) {
return false;
}
}
}
if (fallbackToMeta && !foundMeta) {
return false;
}
}
}
return true;
}
这里处理 annotation 分为两个分支,
这里,重点关注与当前主流程相关的分支 1,既当当前的注解是 @Qualifier 的处理流程。
protected boolean checkQualifier(
BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {
Class<? extends Annotation> type = annotation.annotationType();
RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
// 一、从 Target Class 中找匹配的 @Qualifier
// 首先,从 Target-class 中查找,是否有对应的注解 @Qualifier,使用全名查找 org.springframework.beans.factory.annotation.Qualifier
AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
// 其次,逻辑基本上和上面一样,只是这里使用的是 Qualifier 的 short name: 既 Qualifier,这里所考虑到的一种情况是,万一使用的不是 spring 的 Qualifier Annotation,而是用户自定义的 @Qualifier,那么这里这样处理可以兼容之;
if (qualifier == null) {
qualifier = bd.getQualifier(ClassUtils.getShortName(type));
}
// 如果通过上面两个步骤依然找不到 @Qualifier,则试图从 Factory Method、BeanFactory 中去找...
if (qualifier == null) {
// First, check annotation on qualified element, if any
Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
// Then, check annotation on factory method, if applicable
if (targetAnnotation == null) {
targetAnnotation = getFactoryMethodAnnotation(bd, type);
}
if (targetAnnotation == null) {
RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
if (dbd != null) {
targetAnnotation = getFactoryMethodAnnotation(dbd, type);
}
}
if (targetAnnotation == null) {
// Look for matching annotation on the target class
if (getBeanFactory() != null) {
try {
Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
if (beanType != null) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Not the usual case - simply forget about the type check...
}
}
if (targetAnnotation == null && bd.hasBeanClass()) {
targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
}
}
if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
return true;
}
}
// 二、匹配过程正式开始,
// 深度匹配正式拉开序幕,开始依次深度剖析 Annotation 中的 Attributes
Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
if (attributes.isEmpty() && qualifier == null) {
// If no attributes, the qualifier must be present
return false;
}
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
String attributeName = entry.getKey();// 返回 @Qualifier(value="testBean2") 中的 value
Object expectedValue = entry.getValue();// 从 @Qualifier 中获取的 value 值
Object actualValue = null; // 保存 target-class 中的 @Qualifier value 的实际值
// Check qualifier first 从当前的 target-class 对象去找 @Qualifier 对应的值
if (qualifier != null) {
actualValue = qualifier.getAttribute(attributeName);
}
if (actualValue == null) {
// Fall back on bean definition attribute
actualValue = bd.getAttribute(attributeName);
}
// 最重要的就是 bdHolder.matchesName((String) expectedValue) 方法,比对 target 的 beanname 与 aliasname 是否与 @Qualifier 中的 value 值相匹配
if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
// Fall back on bean name (or alias) match 这里回溯至使用 target 的 bean name 或者是 alias name 的与 @Qualifier 的 value 的匹配方式了
continue;
}
if (actualValue == null && qualifier != null) {
// Fall back on default, but only if the qualifier is present
actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
}
if (actualValue != null) {
actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
}
if (!expectedValue.equals(actualValue)) {
return false;
}
}
return true;
}
上述代码的逻辑主要分为两个部分,
从 target class 中去找与当前 bean 所匹配的 @Qualifier,这里的target class 指的是TestBean class。
根据@Qualifier来匹配适合的 candidate
这里比较重要的一步就是bdHolder.matchesName((String) expectedValue
public boolean matchesName(@Nullable String candidateName) {
//这里的candidateName 即是@Qualifier的value值 即testBean
return (candidateName != null && (candidateName.equals(this.beanName) ||
candidateName.equals(BeanFactoryUtils.transformedBeanName(this.beanName)) ||
ObjectUtils.containsElement(this.aliases, candidateName)));
}
可见,@Autowired 主要是根据 Class Type 去匹配 candidates,如果有多个 candidates,只有当 @Qualifier 匹配失败以后,才会 fall back 至使用 bean name 的方式进行匹配。
如果[通过 Class Type 以及 @Qualifer 寻找 Candidates] 返回多个 candidates,将会使用 @Primary 和 @Priority 继续筛选
DependencyDescriptor#resolveCandidate
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
throws BeansException {
return beanFactory.getBean(beanName, requiredType);
}
这部分参考bean实例化-doGetBean流程
以上。
这里补充一点,除了实现ApplicationAware之外,还可以通过@Autowired注入ApplicationContext,那么ApplicationContext是什么时候注入的,可以参考根据classType和@Qualifier寻找candidates,从已解析的bean中获取并返回
参考:
https://www.shangyang.me/2017/04/05/spring-core-container-sourcecode-analysis-annotation-autowired/
https://blog.csdn.net/chjttony/article/details/6301591