gpt4 book ai didi

spring - @Qualifier 无效

转载 作者:行者123 更新时间:2023-12-05 00:57:23 35 4
gpt4 key购买 nike

我有 3 个数据源,设置如下:

@Configuration
@Component
public class DataSourceConfig {

@Bean("foo")
@ConfigurationProperties(prefix = "spring.datasource.foo")
public DataSource foo() {
DataSource dataSource = DataSourceBuilder.create().build();
return dataSource;
}

@Bean("bar")
@ConfigurationProperties(prefix = "spring.datasource.bar")
public DataSource bar() {
DataSource dataSource = DataSourceBuilder.create().build();
return dataSource;
}

@Bean("baz")
@ConfigurationProperties(prefix = "spring.datasource.baz")
public DataSource baz() {
DataSource dataSource = DataSourceBuilder.create().build();
return dataSource;
}

}

我正在尝试将它们自动连接到我的消费者类中,如下所示:

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyClass {

@Autowired
public MyClass(
@Autowired @Qualifier("foo") DataSource foo,
@Autowired @Qualifier("bar") DataSource bar,
@Autowired @Qualifier("baz") DataSource baz
) {
;
}

}

当应用程序尝试启动时,出现错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.mypackage.MyClass required a single bean, but 3 were found:
- foo: defined by method 'foo' in class path resource [com/example/DataSourceConfig.class]
- bar: defined by method 'bar' in class path resource [com/example/DataSourceConfig.class]
- baz: defined by method 'baz' in class path resource [com/example/DataSourceConfig.class]

为什么 @Qualifier 不起作用?

我正在使用 Spring Boot 1.5.6.RELEASE

最佳答案

通过添加 @Primary 注释使其中一个 bean 成为主要 bean。然后应该识别限定词。

关于spring - @Qualifier 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45578689/

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