本文最后更新于 2025-11-11,文章内容可能已经过时。

1.导入多数据源pom依赖

<!-- 多数据源 -->
		<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot3-starter -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
			<version>4.3.1</version>
		</dependency>

2.配置数据库链接

spring:
  datasource:
    dynamic:
      #主要数据库
      primary: master
      #严格匹配模式,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      strict: false
      datasource:
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/database_1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
          username: database_1
          password: database_1
          type: com.zaxxer.hikari.HikariDataSource
        account:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/database_2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
          username: database_2
          password: database_2
          type: com.zaxxer.hikari.HikariDataSource
        charac:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/database_3?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
          username: database_3
          password: database_3
          type: com.zaxxer.hikari.HikariDataSource
        postal:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/database_4?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
          username: database_4
          password: database_4
          type: com.zaxxer.hikari.HikariDataSource

3.在Mapper上标注@DS

比如我这个mapper是Account数据库

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jam.entities.gameEntities.Accounts;
import org.springframework.stereotype.Repository;

@DS("account")
@Repository
public interface AccountsMapper extends BaseMapper<Accounts> {
}

4.在启动器标注扫描Mapper

@MapperScan("com.jam.mapper.**")

@SpringBootApplication
@EnableCaching
@MapperScan("com.jam.mapper.**")
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}