如何用 SpringBoot 配置多数据源实现过程?
SpringBoot默认会给你自动配好一个数据源,如果要手动配置多数据源那默认的配置就失效了,需要我们手动将默认数据源也配置上,下面直接看例子 来源搞代码网《如何用 SpringBoot 配置多数据源实现过程?》http://www.gaodaima.com/68543.html 默认数据源配置:
// 这个是SpringBoot默认的数据源,一般配置为主数据库 @Configuration @MapperScan(basePackages = "xxx.xxx.test.first.mapper", sqlSessionTemplateRef = "sqlSessionTemplate") public class DataSourceConfig { @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setPlugins(new Interceptor[] {xxx}); // 设置MyBatis插件 return bean.getObject(); } @Bean @Primary public DataSourceTransactionManager testTransactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean @Primary public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }
配置第二个数据源,注意mapper扫描路径和上面的区分开
@Configuration @MapperScan(basePackages = "xxx.xxx.test.second.mapper", sqlSessionTemplateRef = "sqlSessionTemplateSecond") public class DataSourceSecondConfig { // 配置文件需要添加 second.datasource.xxx 数据库的相关配置 @Bean(name = "dataSourceSecond") @ConfigurationProperties(prefix = "second.datasource") public DataSource testDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "sqlSessionFactorySecond") public SqlSessionFactory testSqlSessionFactory(@Qualifier("dataSourceSecond") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setPlugins(new Interceptor[] {xxx}); // 设置mybatis插件 return bean.getObject(); } @Bean(name = "transactionManagerSecond") public DataSourceTransactionManager testTransactionManager(@Qualifier("dataSourceSecond") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionTemplateSecond") public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("sqlSessionFactorySecond") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
配置好后,在 xxx.xxx.test.first.mapper 包下的 mapper 将使用数据源1 ,xxx.xxx.test.second.mapper 包下的 mapper 将使用数据源2