spring boot 添加多数据源
//配置文件 想加几个数据源 就配置几份文件 下面配置文件复制直接使用即可(只需要修改 指定包 和.xml文件 )
@Configuration
//扫描指定包 com.xxx.base
@MapperScan(basePackages = {"com.xxx.base"}, sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class BaseDB {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.base")
@Primary
public DataSource baseDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//指定位置的.xml文件
Resource[] resources = resolver.getResources("classpath:com/xxx/base/mapper/*.xml");
bean.setMapperLocations(resources);
return bean.getObject();
}
@Bean
@Primary
public DataSourceTransactionManager baseTransactionManager(@Qualifier("baseDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
@Primary
public SqlSessionTemplate baseSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
yml文件的配置 (这边我是配置了两个mysql的数据源和一个sqlserver的数据源)
spring:
datasource:
base:
jdbc-url: jdbc:mysql://localhost:3306/xx?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
business:
jdbc-url: jdbc:mysql://localhost:3306/xx?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
other:
jdbc-url: jdbc:sqlserver://localhost:1433;DatabaseName=xx
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: sa
password: 123456
相关依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
快乐的吃干货