Could not autowire. There is more than one bean of 'DataSource' type

前端 未结 3 1747
失恋的感觉
失恋的感觉 2021-02-01 18:06

I\'m trying to Autowire a database by

@Autowired
private DataSource dataSource;

I have one datasource in my application.yml

3条回答
  •  一整个雨季
    2021-02-01 18:14

    Try this it worked for me, use @Primary like this

        @Primary
        @Bean(name ="prodDataSource")
        @ConfigurationProperties(prefix="spring.datasource")
        public DataSource dataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "prodJdbc")
        public JdbcTemplate prodJdbcTemplate(@Qualifier("prodDataSource") DataSource prodDataSource){ 
            return new JdbcTemplate(prodJdbcTemplate);
        }
    
        @Bean(name = "devDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.dev")
        public DataSource devDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "devJdbc")
        public JdbcTemplate devJdbcTemplate(@Qualifier("devDataSource") DataSource devDataSource) {
            return new JdbcTemplate(devDataSource);
        }
    

    And then use @autowire like this

    @Autowired
    @Qualifier("prodJdbc")
    private JdbcTemplate prodJdbcTemplate;
    

    I hope this can help you or someone else :)

提交回复
热议问题