在开发中我们有可能会遇到一个项目需要配置多个数据源,或者需要读写分离的配置,在启动类上贴上@MapperScan注解指定扫描对应的mapper.xml文件肯迪那个是无法满足了。我们可以通过自定义配置数据库配置类来解决这个问题,方式有很多,不同的业务采用的方式也不同,下面我简单的介绍我们项目的使用的方法
比如:项目中我需要连接opretion和device这个两个数据库,且需要进行读写分离,在配置文件中如下:
针对device库我们先创建一个数据库连接配置类
@Configuration
@MapperScan(basePackages = {"com.liuqing.my.repo.device"}, sqlSessionTemplateRef = "deviceSqlSessionTemplate")
public class DeviceDSConfig {
@Value("${props.sql.show}") //定义在配置文件中的字段 ture
private String sqlShow;
}
复制代码
-
@MapperScan
-
basePackages = {"com.liuqing.my.repo.device"}
指定包扫描
-
sqlSessionTemplateRef = "deviceSqlSessionTemplate")
指定sqlSessionTemplateRef
-
在类中添加配置文件中的读写数据源
@ConfigurationProperties(prefix = "spring.shardingsphere.datasource.device.read")
public DataSource deviceReadDataSource() {
return new DruidDataSource();
}
@Bean
@ConfigurationProperties(prefix = "spring.shardingsphere.datasource.device.write")
public DataSource deviceWriteDataSource() {
return new DruidDataSource();
}