Java 如何在带有注释的 Spring 中按名称自动装配?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36183624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:32:34 来源:igfitidea点击:
How to autowire by name in Spring with annotations?
提问by Dims
I have several beans of the same class defined:
我定义了几个相同类的bean:
@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;
}
consequently when I autowire them
因此,当我自动装配它们时
@Autowired
public FieldDescriptor fullSpotField;
@Autowired
public FieldDescriptor annotationIdField;
I get an exception
我得到一个例外
NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ...
How to autowire by name as it possible in XML config?
如何在 XML 配置中尽可能按名称自动装配?
采纳答案by Madhusudana Reddy Sunnapu
You can use @Qualifier
to solve it.
你可以用@Qualifier
它来解决。
In your case you can make:
在您的情况下,您可以:
@Bean(name="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("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;