Spring启动多个数据源

时间:2017-02-28 10:47:10

标签: spring oracle spring-boot datasource

我在1.5.1版本中使用spring boot的应用程序出了问题。

我的应用程序需要与2个数据库(Oracle和MySQL)进行通信

我的应用程序使用2个数据源:       - MySQL数据源

@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);
    }
}
  • Oracle数据源

    @Configuration     公共类MySQLDBConfig {

        @Bean(name = "mysqlDb")
        @ConfigurationProperties(prefix = "spring.ds_mysql")
        public DataSource mysqlDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "mysqlJdbcTemplate")
        public JdbcTemplate mySQLjdbcTemplate(@Qualifier("mysqlDb")DataSource dsMySQL) {
            return new JdbcTemplate(dsMySQL);
        }
    }
    

我已经使用前缀在我的applications.properties中定义了2个数据源。

当我启动程序时出现此错误:

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]

我尝试使用@Primary但是当我需要使用其他数据源时它无法正常工作。

谢谢

2 个答案:

答案 0 :(得分:1)

在Spring启动配置类中添加以下内容

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

样本使用:

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

答案 1 :(得分:0)

或者:

将模板配置与数据源配置分开,并将带有限定符的两个数据源注入模板配置,或者直接调用create datasource方法,例如。

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