Using 2 beans of the same type: javax.sql.DataSource in Spring

前端 未结 4 998
南笙
南笙 2021-01-01 19:45

I am developing a Spring Boot based application in which I would like to create 2 beans: One will point to \'Oracle\' database; the other will point to Hive. I\'ve declar

相关标签:
4条回答
  • 2021-01-01 20:02

    Set one of the beam as @Primary as described in the section 67.2 Configure Two DataSources

    http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-two-datasources

    0 讨论(0)
  • 2021-01-01 20:16

    If you want to use two data sources at the same time and they are not primary and secondary, you should disable DataSourceAutoConfiguration on your application annotated by @SpringBootApplication(excludes = {DataSourceAutoConfiguration.class}).

    Since the DataSourceAutoConfiguration will init the DataSourceInitializer class. The init method in DataSourceInitializer class needs to get DataSource. When there is more than one DataSource, the system gets confused by getting which DataSource.

    @SpringBootApplication(excludes = {DataSourceAutoConfiguration.class}) means that system won't load the DataSourceAutoConfiguration.class when run the application.

    0 讨论(0)
  • 2021-01-01 20:20

    I faced similar issue. Added @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})

    and added manual configuration. It worked!

    0 讨论(0)
  • 2021-01-01 20:22

    Give different names to your beans when using @Bean:

    @Bean(name="bonecpDS")
    public BoneCPDataSource metadataDataSource() {
        //...
    }
    
    @Bean(name="hiveDS")
    public BasicDataSource hiveDataSource() {
        //...
    }
    

    Then, when injecting the bean, use @Qualifier and specify the name of the bean:

    @Component
    public class FooComponent {
        @Autowired
        @Qualifier("bonecpDS")
        DataSource boneCPDataSource;
    }
    
    0 讨论(0)
提交回复
热议问题