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

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


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;
}

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.

Tags:

Java

Spring