gpt4 book ai didi

java - 如何在带有注释的 Spring 中按名称 Autowiring ?

转载 作者:IT老高 更新时间:2023-10-28 13:51:24 24 4
gpt4 key购买 nike

我定义了几个相同类的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;
}

因此当我自动连接它们时

   @Autowired
public FieldDescriptor fullSpotField;

@Autowired
public FieldDescriptor annotationIdField;

我遇到了异常

NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ...

如何在 XML 配置中尽可能按名称 Autowiring ?

最佳答案

你可以使用@Qualifier来解决。

在你的情况下,你可以:

 @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;
}

随后您可以使用以下方法进行注入(inject):

   @Autowired
@Qualifier("fullSpot")
public FieldDescriptor fullSpotField;

@Autowired
@Qualifier("annotationIdSpot")
public FieldDescriptor annotationIdField;

关于java - 如何在带有注释的 Spring 中按名称 Autowiring ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36183624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com