随笔- 659  评论- 133  文章- 0 

Spring Boot通过Configuration配置多数据源

    本文结合SpringBoot + MyBatis + MySql进行多数据源配置,DataSource信息采用自定义dataSource.properties进行配置。

1.文件结构如下:

 

 

 

2.1 pom依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.stu</groupId>
<artifactId>HelloMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<!-- web项目 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
</project>
2.2 启动类:

package com.stu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
@RequestMapping("/app")
public String hello() {
return "ok";
}
}
2.3 properties配置文件:

2.3.1 application.properties

server.port=8080
server.servlet.context-path=/mybatis
spring.freemarker.prefix=/views
spring.freemarker.suffix=.html
2.3.2 dataSource.properties

spring.datasource.base.url=jdbc:mysql://localhost:3306/test1
spring.datasource.base.username=root
spring.datasource.base.password=root
spring.datasource.base.driverClassName=com.mysql.jdbc.Driver

spring.datasource.slave.url=jdbc:mysql://localhost:3306/test2
spring.datasource.slave.username=root
spring.datasource.slave.password=root
spring.datasource.slave.driverClassName=com.mysql.jdbc.Driver
2.4 读取properties文件,并封装成实体类

2.4.1 base数据源配置实体类

package com.stu.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
/*指定配置文件名,默认从classpath下寻找该文件,也就是等同于classpath:dataSource.properties
* 可以指定多个文件
*/
@PropertySource(value = { "dataSource.properties" })
/*
* 指定前缀,读取的配置信息项必须包含该前缀,且除了前缀外,剩余的字段必须和实体类的属性名相同,
* 才能完成银映射
*/
@ConfigurationProperties(prefix = "spring.datasource.base")
public class DB1Config {
private String url;
private String username;
private String password;
private String driverClassName;
getter/setter...

}
2.4.2 slave数据源配置实体类

package com.stu.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = { "dataSouce.properties" })
@ConfigurationProperties(prefix = "spring.datasource.slave")
public class DB2Config {
private String url;
private String username;
private String password;
private String driverClassName;
setter/getter...

}
2.5 数据源配置类:

2.5.1 DB1Configuration

package com.stu.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//只从com.stu.dao包下读取dao文件,并且该报下的dao使用本datasource
@MapperScan(basePackages = "com.stu.dao", sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class DB1Configuration {
@Bean(name = "baseDataSource")
//对于多数据源,必须制定primary,否则报错有2个datasource,并且,只能制定一个primary
@Primary
//从DB1Config从获取配置信息
public DataSource setDataSource(DB1Config dbc) {
DruidDataSource ds = new DruidDataSource();
ds.setUrl(dbc.getUrl());
ds.setUsername(dbc.getUsername());
ds.setPassword(dbc.getPassword());
ds.setDriverClassName(dbc.getDriver());
return ds;
}

@Bean(name = "baseSqlSessionFactory")
@Primary
public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//指定mapper.xml文件存放位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/base/*.xml"));
return bean.getObject();
}

@Bean(name = "baseSqlSessionTemplate")
@Primary
public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.5.2 DB2Configuration

package com.stu.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//只从com.stu.test2dao包下读取dao文件,并且该报下的dao使用本datasource
@MapperScan(basePackages = "com.stu.test2dao", sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class DB2Configuration {
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource setDataSource(DB2Config dbc) {
DruidDataSource ds = new DruidDataSource();
ds.setUrl(dbc.getUrl());
ds.setUsername(dbc.getUsername());
ds.setPassword(dbc.getPassword());
ds.setDriverClassName(dbc.getDriver());
return ds;
}

@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory setSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
return bean.getObject();
}

@Bean(name = "slaveSqlSessionTemplate")
public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.6 Mapper文件

2.6.1 userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.stu.dao.UserDao" >
<insert id="insert" parameterType="java.util.Map">
insert into user (id, name, age) values (#{id}, #{name}, #{age});
</insert>
</mapper>
2.6.2 userTest2Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.stu.test2dao.UserDao2" >
<insert id="insert" parameterType="java.util.Map">
insert into user2 (id, name, age) values (#{id}, #{name}, #{age});
</insert>
</mapper>
2.7 Dao类:

2.7.1 UserDao

package com.stu.dao;
import org.apache.ibatis.annotations.Param;
public interface UserDao {
void insert(@Param("id") Integer id, @Param("name")String name, @Param("age")Integer age);
}
2.7.2 UserDao2

package com.stu.test2dao;
import org.apache.ibatis.annotations.Param;
public interface UserDao2 {
void insert(@Param("id") Integer id, @Param("name")String name, @Param("age")Integer age);
}
2.8 Service

package com.stu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stu.dao.UserDao;
import com.stu.test2dao.UserDao2;

@Service
public class UserService {
@Autowired
private UserDao dao1;
@Autowired
private UserDao2 dao2;

public void createUser1(Integer id, String name, Integer age) {
dao1.insert(id, name, age);
}

public void createUser2(Integer id, String name, Integer age) {
dao2.insert(id, name, age);
}
}
2.9 Controller

package com.stu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.stu.service.UserService;

@RestController
public class UserController {

@Autowired
UserService userService;

@RequestMapping("/add")
public String createUser1(Integer id, String name, Integer age) {
userService.createUser1(id, name, age);
return "ok";
}
@RequestMapping("/add2")
public String createUser2(Integer id, String name, Integer age) {
userService.createUser2(id, name, age);
return "ok";
}

————————————————

参考链接:https://blog.csdn.net/houfengfei668/article/details/79947032

     https://blog.csdn.net/qq_28060549/article/details/82077705

 

posted on 2019-12-01 14:18  @ 小浩  阅读(...)  评论(...编辑  收藏