Spring启动多个数据源

Posted

技术标签:

【中文标题】Spring启动多个数据源【英文标题】:Spring boot multiple datasources 【发布时间】:2017-07-19 07:10:16 【问题描述】:

我在 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 数据源

@配置 公共类 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,但是当我需要使用其他数据源时它不起作用。

谢谢

【问题讨论】:

您遇到的错误是什么? 【参考方案1】:

在你的 Spring Boot 配置类中添加以下内容

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

【讨论】:

默认情况下,spring boot 启用 DatasourceAutoConfiguration,它初始化 DatasourceInitializer 以从类路径运行 schema.sql 和 data.sql。这需要您的案例中缺少的单个或主要数据源。所以需要禁用它。【参考方案2】:

要么:

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

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

【讨论】:

以上是关于Spring启动多个数据源的主要内容,如果未能解决你的问题,请参考以下文章

在春季批处理(spring-boot-1.5.2.RELEASE)中使用多个数据源在启动时引发异常

在 Spring 中使用多个数据源

多租户:使用 Spring Data JPA 管理多个数据源

spring-boot 应用程序不会将夹具加载到多个数据源之一

Spring Boot 动态数据源(Spring 注解数据源)

Spring Boot(十二):MyBatis-Plus的多数据源和分页