# mybatis多数据源配置 ## dynamic-datasource ### 1、引入依赖 4.1.3版本是稳定版 ```xml com.baomidou dynamic-datasource-spring-boot-starter 4.1.3 ``` ### 2、配置数据源 需要注意的是,这里使用了druid,p6spy 需要配置对应的数据源,使用primary来指明默认的数据源 ```yml #配置数据源 spring: autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure datasource: dynamic: primary: db1 datasource: db1: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:stand_lms}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true username: ${DB_USER:root} password: ${DB_PWD:12356} type: com.alibaba.druid.pool.DruidDataSource db2: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:13306}/${DB_NAME:test}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true username: ${DB_USER:root} password: ${DB_PWD:12356} type: com.alibaba.druid.pool.DruidDataSource ``` 集成了druid需要去除druid配置 ```yml autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure ``` 去除框架原来对druid数据源的配置类 ```java //import com.alibaba.druid.pool.DruidDataSource; //import lombok.extern.slf4j.Slf4j; //import org.springframework.boot.context.properties.ConfigurationProperties; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Primary; // //import javax.sql.DataSource; // //@Configuration //@Slf4j //public class DataBaseConfig { // // @Primary // @Bean(name = "dataSource") // @ConfigurationProperties(prefix = "spring.datasource.druid") // public DataSource dataSource() { // return new DruidDataSource(); // } // //} ``` 排除掉DruidDataSourceAutoConfigure 在启动类中需要排除掉DruidDataSourceAutoConfigure.class,就是取消Druid的数据源的自动配置类。 ```java @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DruidDataSourceAutoConfigure.class }) ``` 也可以在配置类中 ```yml autoconfigure: exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure ``` ### 3、测试 使用@DS("db2")注解实现切换数据源 ```java public interface TestMapper extends BaseMapper { @DS("db2") JSONObject getAll13(); } ```