Ahmed
Ahmed

Reputation: 385

Spring boot multiple datasources

I have a problem with an application using spring boot in 1.5.1 version.

My application need to communicate with 2 databases (Oracle and MySQL)

My application use 2 datasources : - MySQL datasource

@Configuration
public class OracleDBConfig {

    @Bean(name = "oracleDb")
    @ConfigurationProperties(prefix = "spring.ds_oracle") 
    public DataSource oracleDataSource() {
        return  DataSourceBuilder.create().build();
    }

    @Bean(name = "oracleJdbcTemplate")
    public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDb") DataSource dsOracle) {
        return new JdbcTemplate(dsOracle);
    }
}

I have defined the 2 datasources in my applications.properties by using the prefix.

When I launch the program I have this error :

Parameter 0 of method oracleJdbcTemplate in com.bv.aircraft.config.OracleDBConfig required a single bean, but 2 were found:
    - mysqlDb: defined by method 'mysqlDataSource' in class path resource [com/bv/aircraft/config/MySQLDBConfig.class]
    - oracleDb: defined by method 'oracleDataSource' in class path resource [com/bv/aircraft/config/OracleDBConfig.class]

I have tried to use @Primary but it is not working when i need to use the other datasource.

Thank you

Upvotes: 1

Views: 961

Answers (2)

Monzurul Shimul
Monzurul Shimul

Reputation: 8386

Add following in your spring boot configuration class

@EnableAutoConfiguration(exclude = {DataSourceTransactionManagerAutoConfiguration.class, DataSourceAutoConfiguration.class})

Sample Usage:

@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceTransactionManagerAutoConfiguration.class, DataSourceAutoConfiguration.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Upvotes: 2

PaulNUK
PaulNUK

Reputation: 5209

Either:

separate the template configuration from the datasource configuration and inject in the two datasources with qualifiers into the template configuration, or just call the create datasource method directly, e.g.

public JdbcTemplate oracleJdbcTemplate(oracleDataSource()) DataSource dsOracle) {
    return new JdbcTemplate(dsOracle);
}

Upvotes: 0

Related Questions