@Qualifier注解通常和@Autowired注解一起使用,那么首先来看@Autowire是怎么把Bean对象注入到Spring容器中的。
前置条件:需要读者了解@Autowired
是如何将类注入进来的。
深入解析 Spring Framework 中 @Autowired 注解的实现原理
在阅读代码之前,先引用著名作者:江南一点雨-松哥写的demo。
定义一个类B,在JavaConfig中定义了两个关于B的Bean,b1和b2,在A类中注入。
public class B {
private String name;
}
@Configuration
@ComponentScan
public class JavaConfig {
@Bean(value = "b1")
@Qualifier
B b1() {
return new B();
}
@Bean("b2")
B b2() {
return new B();
}
}
@Component
public class A {
@Autowired
@Qualifier
B b;
}
此时如果不使用@Qualifier
注解会报错:
根据错误提示来看,类A需要一个单例的Bean,但是找到了两个Bean,通过前文关于@Autowired
注解的解析,我们可以知道@Autowired
注解是根据类型找到对应的Bean进行注入,由于Bean-b1和b2都是B类型的,所以如果单独使用@Autowired
注解是无法将b1、b2注入的,那么@Qualifier做了什么,使Bean正常注入了呢?请看下文。
接上文DefaultListableBeanFactory类的doResolveDependency()
方法,该方法会解析类中注入的各个Bean的信息,并通过方法匹配到一个或多个Bean。
//获取注入的Bean信息
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
//匹配Bean
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
//当匹配到的Bean Map是一个空时的处理逻辑-抛异常
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
当匹配到的Bean Map是一个空时,会抛出一个我们比较常见的Exception:
NoSuchBeanDefinitionException
Spring Framework中的依赖注入(Dependency Injection)实现逻辑,负责解决多个候选Bean与依赖项之间的关系,特别是处理数组、集合和Map类型的依赖项,这段逻辑会根据不同类型Bean执行不同的处理逻辑,确保正确的候选Bean被注入到依赖项中。
@Nullable
private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {
Class<?> type = descriptor.getDependencyType();
if (descriptor instanceof StreamDependencyDescriptor) {
// 处理流类型的依赖项
// 查找匹配的候选Bean
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()) {
// 处理数组类型的依赖项
// 查找匹配的候选Bean
// 然后将这些候选Bean转换为数组
// 如果需要,可以根据排序比较器对数组进行排序
// 返回最终结果
}
else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
// 处理集合类型的依赖项
// 查找匹配的候选Bean
// 然后将这些候选Bean转换为集合
// 如果需要,可以根据排序比较器对集合进行排序
// 返回最终结果
}
else if (Map.class == type) {
// 处理Map类型的依赖项
// 查找匹配的候选Bean
// 返回匹配的候选Bean
}
else {
// 其他情况,返回null
return null;
}
// 其他代码省略
}
通过注释可以看到,该方法的作用是查找与所需类型匹配的 Bean 实例,结合@Qualifier
注解的作用是明确注入的Bean来看,该方法中会存在@Qualifier
注解的逻辑处理。
/**
* Find bean instances that match the required type.
* Called during autowiring for the specified bean.
* @param beanName the name of the bean that is about to be wired
* @param requiredType the actual type of bean to look for
* (may be an array component type or collection element type)
* @param descriptor the descriptor of the dependency to resolve
* @return a Map of candidate names and candidate instances that match
* the required type (never {@code null})
* @throws BeansException in case of errors
* @see #autowireByType
* @see #autowireConstructor
*/
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 = CollectionUtils.newLinkedHashMap(candidateNames.length);
//...省略...
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;
}
重点代码:
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
大家看我的条件断点:
由上文的demo代码可知,我在A类中注入了两个B类型的Bean:b1和b2,那么在Spring启动时,框架本身就会查找候选的依赖关系和Bean,并将Bean注入,所以在此时便会获取到b1、b2。该功能的实现是依赖于:BeanFactoryUtils.beanNamesForTypeIncludingAncestors()
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;
}
Java中运行多重继承,因此该方法使用了递归查询
请详细看一下这段代码:
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
在执行判断当前beanName是否为候选的注入Bean前,会调用四次isAutowireCandidate方法。
protected boolean isAutowireCandidate(
String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
throws NoSuchBeanDefinitionException {
String bdName = BeanFactoryUtils.transformedBeanName(beanName);
if (containsBeanDefinition(bdName)) {
return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(bdName), descriptor, resolver);
}
else if (containsSingleton(beanName)) {
return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
}
BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory dlbf) {
// No bean definition found in this factory -> delegate to parent.
return dlbf.isAutowireCandidate(beanName, descriptor, resolver);
}
else if (parent instanceof ConfigurableListableBeanFactory clbf) {
// If no DefaultListableBeanFactory, can't pass the resolver along.
return clbf.isAutowireCandidate(beanName, descriptor);
}
else {
return true;
}
}
最后会到达AutowireCandidateResolver接口,查看接口实现,QualifierAnnotationAutowireCandidateResolver
是@Qualifier注解的处理逻辑。
/**
* Determine whether the provided bean definition is an autowire candidate.
* <p>To be considered a candidate the bean's <em>autowire-candidate</em>
* attribute must not have been set to 'false'. Also, if an annotation on
* the field or parameter to be autowired is recognized by this bean factory
* as a <em>qualifier</em>, the bean must 'match' against the annotation as
* well as any attributes it may contain. The bean definition must contain
* the same qualifier or match by meta attributes. A "value" attribute will
* fallback to match against the bean name or an alias if a qualifier or
* attribute does not match.
* @see Qualifier
*/
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
boolean match = super.isAutowireCandidate(bdHolder, descriptor);
if (match) {
match = checkQualifiers(bdHolder, descriptor.getAnnotations());
if (match) {
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;
}
第一步首先调用父类的isAutowireCandidate
进行校验匹配。
@Override
public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
if (!super.isAutowireCandidate(bdHolder, descriptor)) {
// If explicitly false, do not proceed with any other checks...
return false;
}
return checkGenericTypeMatch(bdHolder, descriptor);
}
在Debug中查看:
A类中通过@Autowired
注解了B类型的Bean b1,因此,通过调用父类的isAutowireCandidate
方法返回true,进行下一步判断。
接下来执行checkQualifiers。
Match the given qualifier annotations against the candidate bean definition.
翻译:将给定的注解去匹配所有候选Bean定义,以确定使用哪个Bean进行装配。
在Spring自动装配机制中,当存在多个类型相同的Bean时,自动装配可能会失败,因此Spring无法知道使用哪个Bean,此时,可以使用限定符(@Qualifier)来指定所需要的Bean。
/**
* Match the given qualifier annotations against the candidate bean definition.
*/
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)) {
if (!checkQualifier(bdHolder, annotation, typeConverter)) {
fallbackToMeta = true;
}
else {
checkMeta = false;
}
}
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 && ObjectUtils.isEmpty(AnnotationUtils.getValue(metaAnn))) ||
!checkQualifier(bdHolder, metaAnn, typeConverter)) {
return false;
}
}
}
if (fallbackToMeta && !foundMeta) {
return false;
}
}
}
return true;
}
在这段代码中,入参是:
注解是一种元数据,它提供了一种在代码中添加、附加额外信息的方式。通过注解,可以为类、方法、字段等元素添加标记和属性,以便在运行时可以基于这些注解进行一些特定的处理逻辑。
在获取到的注解中轮询,针对@Qualifier
注解单独处理。所以,在for循环中会判断注解的类型是否为@Qualifier
。
/**
* Checks whether the given annotation type is a recognized qualifier type.
*/
protected boolean isQualifier(Class<? extends Annotation> annotationType) {
for (Class<? extends Annotation> qualifierType : this.qualifierTypes) {
if (annotationType.equals(qualifierType) || annotationType.isAnnotationPresent(qualifierType)) {
return true;
}
}
return false;
}
当判断为注解是@Qualifier
时,开始执行@Qualifier
注解最核心的一块逻辑:
protected boolean checkQualifier(
BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {
Class<? extends Annotation> type = annotation.annotationType();
RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
if (qualifier == null) {
qualifier = bd.getQualifier(ClassUtils.getShortName(type));
}
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) {
BeanFactory beanFactory = getBeanFactory();
// Look for matching annotation on the target class
if (beanFactory != null) {
try {
Class<?> beanType = beanFactory.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;
}
}
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();
Object expectedValue = entry.getValue();
Object actualValue = null;
// Check qualifier first
if (qualifier != null) {
actualValue = qualifier.getAttribute(attributeName);
}
if (actualValue == null) {
// Fall back on bean definition attribute
actualValue = bd.getAttribute(attributeName);
}
if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
expectedValue instanceof String name && bdHolder.matchesName(name)) {
// Fall back on bean name (or alias) match
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;
}
@Qualifier
,如果是自定义注解继承自@Qualifier
,则拿到的是自定义注解。@Qualifier
注解,如果在RootBeanDefinition中可以获取到注解,则开始执行通过元数据工具类获取元数据属性逻辑。@Qualifier
注解中定义的相关信息。targetAnnotation
,则使用RootBeanDefinition对象通过getResolvedDecoratedDefinition方法获取。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();
Object expectedValue = entry.getValue();
...
}
引用江南一点雨大佬的一段总结:
以上就是 checkQualifier 方法完整的比较流程。总结一下,其实就两步: