我写了一个示例程序如下。
@Configuration
public class MyclassName{
private final List<String> tableIds;
public MyclassName(
List<String> tableIds) {
this.tableIds = tableIds;
}
}
运行时,我得到下面的错误。
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in MyclassName required a single bean, but 4 were found:
- spring.sleuth.baggage-keys: defined by method 'baggageKeys' in class path resource [org/springframework/cloud/sleuth/autoconfig/TraceBaggageConfiguration.class]
- spring.sleuth.local-keys: defined by method 'localKeys' in class path resource [org/springframework/cloud/sleuth/autoconfig/TraceBaggageConfiguration.class]
- spring.sleuth.propagation-keys: defined by method 'propagationKeys' in class path resource [org/springframework/cloud/sleuth/autoconfig/TraceBaggageConfiguration.class]
- spring.sleuth.log.slf4j.whitelisted-mdc-keys: defined by method 'whiteListedMDCKeys' in class path resource [org/springframework/cloud/sleuth/autoconfig/TraceBaggageConfiguration.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
Process finished with exit code 0
我们使用sleuth进行跟踪,所以pom.xml也有依赖关系。但这是一个非常基本的例子,为什么我会得到这个错误。有人能帮助吗?
3条答案
按热度按时间j91ykkif1#
类
MyclassName
对于spring框架是已知的。所以spring会尝试使用构造函数来创建
MyclassName
的一个示例:Parameter 0 of constructor in MyclassName
是List<String> tableIds
Spring试图为这个参数提供一个值,但是它找到了4,而不是只有一个可用的值。所以Spring不够聪明,不应该选择一个代替你。
4个可用值由Sleuth提供,并在TraceBaggageConfiguration.class中声明,如下所示:
为了解决这种犹豫不决的问题,您需要通过使用唯一标识符来告诉Spring您真正想要在构造函数中注入哪个
List<String>
。首先限定(给予一个id)预期的bean
然后使用
org.springframework.beans.factory.annotation.Qualifier
注解告诉Spring您真正想要的bean:baubqpgj2#
这意味着你的
MyclassNames
,作为Spring
中的一个Configuration
bean,需要注入一个类型为List<String>
的bean,碰巧slueth
的TraceBaggageConfiguration
类定义了一些类型为List<String>
的bean:因此
spring
报告了一个错误,不知道要注入哪个bean。您可能需要使用Qualifier
来指定要注入的bean。或者,您是否定义了对应的bean,该bean散列了需要注入的List<String>
类型?MyclassName
中的List<String> tableIds
是什么?您需要如下定义Bean
:或者,您可以使用,在本例中,tableId将为
null
:5ssjco0h3#
不管怎样,因为我发现这篇文章在寻找相同的错误消息,所以我在Sping Boot 中使用Lombok的
@RequiredArgsConstructor
注入List<String>
:并通过手动初始化列表修复了该问题:
然后用Spring属性正确地填充该列表。