Spring 启动多个数据源

Spring boot multiple datasources

我在 1.5.1 版本中使用 spring 启动的应用程序有问题。

我的应用程序需要与 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);
    }
}

我已经在 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,但当我需要使用其他数据源时它不起作用。

谢谢

或者:

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

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

在您的 spring 引导配置中添加以下内容 class

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