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

前端 未结 3 1745
失恋的感觉
失恋的感觉 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:11

    I solved by adding qualifier above the property:

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2021-02-01 18:19

    Please note that Spring Boot autoconfigured beans are not supported 100% yet, see https://youtrack.jetbrains.com/issue/IDEA-139669 for progress and possible workaorunds.

    0 讨论(0)
提交回复
热议问题