我有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。然后应该识别出限定词。

10-06 13:03