springboot+druid+mybatisplus 配置多数据源
时间: 2025-05-03 17:21:57 浏览: 28
在Spring Boot项目中配置多数据源通常会用到Druid作为数据库连接池,MyBatisPlus作为ORM框架,以及Spring Cloud Config或YAML文件来管理不同的数据库配置。以下是基本步骤:
1. 添加依赖:首先,在`pom.xml`或`build.gradle`中添加对应的依赖,如Druid、MyBatis Plus的Spring Boot Starter和Spring Cloud Config(如果使用)。
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<!-- 如果你想从配置服务器获取数据源信息 -->
</dependency>
```
2. 配置数据源:在`application.yml`或`application.properties`中,创建两个或更多数据源,例如`dev.datasource`和`prod.datasource`。
```yaml
spring:
cloud:
config:
uri: http://config-server-url:8888 # 如果使用Config Server
profiles:
active: dev
datasource:
dev:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/dev_db?serverTimezone=UTC
username: user_dev
password: pass_dev
prod:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://db-prod.example.com:3306/prod_db?serverTimezone=UTC
username: user_prod
password: pass_prod
```
通过`spring.profiles.active`切换活跃的数据源。
3. 创建数据源bean:在`DataSourceAutoConfiguration`或自定义配置类中,根据当前的环境(Profile)动态配置数据源。
4. MyBatis Plus集成:在MyBatis Plus的全局配置类中,设置自动扫描映射器,同时指定使用的DataSource。
```java
@Configuration
public class GlobalConfig {
@Autowired
private DataSource dataSource;
@Bean
public GlobalConfig globalConfig() {
GlobalConfig config = new GlobalConfig();
config.setDataSource(dataSource);
// 可能需要其他配置,如MapperScannerConfigurer等
return config;
}
}
```
5. 按需启用:在需要使用特定数据源的地方,使用注解或基于配置的对象选择正确的数据源,比如`@Database`或`DbUtil.selectByDbType()`。
阅读全文
相关推荐


















