如何在SpringBoot工程中配置多数据源呢?
1. 排除掉自动引入的数据源相关配置
代码语言:javascript复制@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
代码语言:javascript复制// 这里以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
数据源的配置类
代码语言:javascript复制@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
数据源的配置类
代码语言:javascript复制@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);
}
}
这个演示比较简单,会再更新为更贴切为实际中的配置。