Spring @Qualifier和@Autowire不起作用

时间:2016-12-21 17:47:27

标签: spring dependency-injection autowired

Whole Source Code has the problem below

我正在使用两个数据库。所以我添加了两个不同名称的数据源。当我以为我注入适当的数据源。我在下面遇到了意外错误。我的代码有什么问题?

我的application.yml文件

<pre>
@Configuration
public class DBConfig {

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

    @Bean(name = "srcJdbcTemplate")
    public JdbcTemplate srcJdbcTemplate(@Qualifier("srcDataSource") DataSource srcDataSource) {
    return new JdbcTemplate(srcDataSource);
    }

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

    @Bean(name = "dstJdbcTemplate")
    public JdbcTemplate dstJdbcTemplate(@Qualifier("dstDataSource") DataSource dstDataSource) {
    return new JdbcTemplate(dstDataSource);
    }
}
</pre>

我的DBConfig.java文件

<pre>
@Component
public class DBImporter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired @Qualifier("srcDataSource")
    public DataSource srcDataSource;

    @Autowired @Qualifier("srcJdbcTemplate")
    public JdbcTemplate srcJdbcTemplate;

    @Autowired @Qualifier("dstDataSource")
    public DataSource dstDataSource;

    @Autowired @Qualifier("dstJdbcTemplate")
    public JdbcTemplate dstJdbcTemplate;
}
</pre>

我的DBImporter.java文件

<pre>
***************************
APPLICATION FAILED TO START
***************************

Description:

Field srcDataSource in com.cku.assmt.dbimp.DBImporter required a single bean, but 2 were found:
    - srcDataSource: defined by method 'srcDataSource' in class path resource [com/cku/assmt/dbimp/DBConfig.class]
    - dstDataSource: defined by method 'dstDataSource' in class path resource [com/cku/assmt/dbimp/DBConfig.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
</pre>

我得到了这个错误。

{{1}}

1 个答案:

答案 0 :(得分:0)

不是使用@Bean(name =&#34; myName&#34;),而是在方法上使用两个注释:@Bean @Qualifier(&#34; myName&#34;)