1.引入依赖
复制xml代码<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency>
2.配置数据源
在application.properties
数据源信息配置在文件中:
properties复制代码代码# Spring.datasource.url=jdbc:mysql://localhost:3306/main_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# Spring从数据源配置.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/master_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.master.username=rootspring.dynamic.datasource.master.password=rootspring.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driverspring.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.slave.username=rootspring.dynamic
properties复制代码代码# Spring.datasource.url=jdbc:mysql://localhost:3306/main_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# Spring从数据源配置.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/master_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.master.username=rootspring.dynamic.datasource.master.password=rootspring.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driverspring.dynamic.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8spring.dynamic.datasource.slave.username=rootspring.dynamic