本文介绍了如何使用注释在Spring中按名称自动装配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义了几个相同类的bean:
I have several beans of the same class defined:
@Bean
public FieldDescriptor fullSpotField() {
FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
return ans;
}
@Bean
public FieldDescriptor annotationIdField() {
FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
return ans;
}
因此当我自动装货时
@Autowired
public FieldDescriptor fullSpotField;
@Autowired
public FieldDescriptor annotationIdField;
我得到例外
NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ...
如何在XML配置中按名称自动装配?
How to autowire by name as it possible in XML config?
推荐答案
你可以使用 @Qualifer
来解决它。
在你的情况下,你可以:
In your case you can make:
@Bean
@Qualifier("fullSpot") // Not mandatory. If not specified, it takes the method name i.e., "fullSpotField" as qualifier name.
public FieldDescriptor fullSpotField() {
FieldDescriptor ans = new FieldDescriptor("full_spot", String.class);
return ans;
}
@Bean
@Qualifier("annotationIdSpot") // Same as above comment.
public FieldDescriptor annotationIdField() {
FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class);
return ans;
}
随后您可以使用以下注入:
and subsequently you can inject using:
@Autowired
@Qualifier("fullSpot")
public FieldDescriptor fullSpotField;
@Autowired
@Qualifier("annotationIdSpot")
public FieldDescriptor annotationIdField;
这篇关于如何使用注释在Spring中按名称自动装配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!