Spring Boot学习笔记(六)mybatis配置多数据源

application.properties

#数据库配置
#数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #我用的是springBoot 2.1 不需要配置驱动,配置驱动的话反而会出现警告
#spring.datasource.url=jdbc:mysql://192.168.238.130:3306/dev?useUniode=true&characterEncoding=utf-8
#spring.datasource.username=root
#spring.datasource.password=123 #把前缀替换成自定义的,后缀不能变
#在方法中根据特定的前缀获取数据源连接信息
data1.url=jdbc:mysql://192.168.238.130:3306/dev?useUniode=true&characterEncoding=utf-8
data1.username=root
data1.password=123 data2.url=jdbc:mysql://192.168.238.130:3306/dev_1?useUniode=true&characterEncoding=utf-8
data2.username=root
data2.password=123

DataBaseConfig

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
@MapperScan(basePackages={"com.sc.myboot.dao"},sqlSessionFactoryRef = "MySqlSessionFactory1")
public class DataBaseConfig { @Value("${spring.datasource.type}")
private Class<? extends DataSource> dataSourceType; @Bean(name = "MyDataSource1")
@ConfigurationProperties(prefix = "data2")
public DataSource getDataSource(){
return DataSourceBuilder.create().type(dataSourceType).build();
} @Bean(name = "MySqlSessionFactory1")
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("MyDataSource1") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
return sessionFactory.getObject();
} }

我的配置方法比较简单,即按包分离,在制定的包范围内,注入指定的SqlSessionFactory

图解

Spring Boot学习笔记(六)mybatis配置多数据源

上一篇:1210笔记//关于导航实例-QQ空间//导航实例-storyboard实现//控制器的生命周期//控制器的生命周期方法


下一篇:Flex性能优化常用手法总结 转