作者 | 山高人为峰ws
来源 | urlify.cn/M7RZzq
场景分析:在同一个项目中可能会遇到需要连接操作多个数据库,如果是这种情况下的话,我们在application.yml中数据源的配置就无法满足这种需求,那怎么解决呢?我们只能通过java config的方式去配置多数据源,从而满足需求。
1.首先看下application.yml关于数据源的配置(其实这里的配置和传统的一样)
mybatis:
mapperLocations: classpath:/mapper/*.xml
configuration:
call-setters-on-nulls: true
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://localhost:3306/zjuap #mysql配置
driver-class-name: com.mysql.jdbc.Driver #mysql配置
#url: jdbc:oracle:thin:@127.0.0.1:1521:orcl #oracle配置
#driver-class-name: oracle.jdbc.OracleDriver #oracle配置
username: zjft
#密码加密 java -cp druid-1.1.10.jar com.alibaba.druid.filter.config.ConfigTools you_password
#密码为加密的 zjft8888
password: MA+imF+ye4ptAG+nuJsA/RYs8MZPTXotRC0DBdR5rFeAXHL8h7kxFJEcmukugC1N7g==
initial-size: 10
max-active: 20
min-idle: 4
max-wait: 60000
validation-query: SELECT 1 #mysql配置
#validation-query: select 1 from dual #oracle配置
validation-query-timeout: 30000
#配置连接属性,是否开启密码加密,以及配置加密加密的公钥 public key
connection-properties: config.decrypt=true;config.decrypt.key=MFwwDQYJQ/BRnCnkCAwEAAQ==
filter:
config:
enabled: true #如果启用密码加密配置的话,这里必须开启,目的是注入密码加解密过滤器
2.相关依赖添加
<!--ORM框架-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
<scope>runtime</scope>
</dependency>
3.接下来就是java config的配置
@Configuration
@ConditionalOnMissingBean({Marker.class}) //这里是我的自动装配条件注解
@MapperScan(basePackages = "com.zjft.uap.mapper.dao", sqlSessionTemplateRef = "zjuapSqlSessionTemplate")
public class DefaultDBSourceConfiguration {
/**
* 创建主数据源对象,注入到Spring
* 可扩展多个数据源
*/
@Bean(name = "zjuapDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid") //注意这里,读取application.yml配置
public DataSource dataSource(ConfigFilter configFilter) {
// 这里是个坑,如果自定义数据源需要对密码加密的话,必须要加上这个过滤器,否则连接会报错
DruidDataSource dataSource = new DruidDataSource();
/* 下面的这个ConfigFilter必须得加,否则在application.yml中配置密码加密,在启动项目时会报错
* [com.alibaba.druid.pool.DruidDataSource] [ERROR] create connection SQLException, url: jdbc:mysql://localhost:3306/zjuap, errorCode 1045, state 28000 *java.sql.SQLException: Access denied for user 'zjft'@'localhost' (using password: YES)
*/
List filters = new ArrayList<ConfigFilter>(){{
add(configFilter);
}};
dataSource.setProxyFilters(filters);
return dataSource;
}
/**
* 从配置文件获取主数据源的连接信息
*/
@Value("${mybatis.mapperLocations}")
private String mapperLocation;
@Bean
public DatabaseIdProvider databaseIdProvider(){
DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties p = new Properties();
p.setProperty("Oracle", "oracle");
p.setProperty("MySQL", "mysql");
databaseIdProvider.setProperties(p);
return databaseIdProvider;
}
/**
*创建SqlSessionFactory
*/
@Bean(name = "zjuapSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("zjuapDataSource") DataSource dataSource, MybatisProperties mybatisProperties) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
bean.setConfiguration(mybatisProperties.getConfiguration());
bean.setDatabaseIdProvider(databaseIdProvider());
bean.setVfs(SpringBootVFS.class);
return bean.getObject();
}
/**
* 配置事务
*/
@Bean(name = "zjuapTransactionManager")
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("zjuapDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
/**
*创建SqlSessionTemplate
*/
@Bean(name = "zjuapSqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("zjuapSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}