如何在SpringBoot工程中配置多数据源呢?

1. 排除掉自动引入的数据源相关配置

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class,
    JdbcTemplateAutoConfiguration.class
})
public class HelloJdbcApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloJdbcApplication.class, args);
    }

}

2. 新增数据源配置信息 application.properties

// 这里以H2演示,后面更新

foo.datasource.url=jdbc:h2:mem:foo
foo.datasource.username=sa
foo.datasource.password=

bar.datasource.url=jdbc:h2:mem:bar
bar.datasource.username=sa
bar.datasource.password=

3. 新增数据源配置类

3.1 foo 数据源的配置类

@Configuration
public class FooDataSourceConfiguration {

    @Bean
    @ConfigurationProperties("foo.datasource")
    public DataSourceProperties fooDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource fooDataSource() {
        DataSourceProperties dataSourceProperties = fooDataSourceProperties();
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean
    @Resource
    public PlatformTransactionManager fooTxManager(DataSource fooDataSource) {
        return new DataSourceTransactionManager(fooDataSource);
    }
}

3.2 bar 数据源的配置类

@Configuration
public class BarDataSourceConfiguration {

    @Bean
    @ConfigurationProperties("bar.datasource")
    public DataSourceProperties barDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource barDataSource() {
        DataSourceProperties dataSourceProperties = barDataSourceProperties();
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean
    @Resource
    public PlatformTransactionManager barTxManager(DataSource barDataSource) {
        return new DataSourceTransactionManager(barDataSource);
    }
}

这个演示比较简单,会再更新为更贴切为实际中的配置。


借着极客时间的付费课程《玩转Spring全家桶》的机会,系统性的对Spring家族做些学习和了解。
如果你也有对这个课程的学习需求,可以通过此链接进行购买,我会得到极客的返利。