1、配置dynamic多数据源
①在项目的 pom.xml 中引入:
<!-- 多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
</dependency><!-- druid 官方 starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
②修改 application-dev.yml 配置文件(根据自己项目的配置文件自行修改)
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认master
strict: false #是否严格匹配数据源,默认false,true未匹配到指定数据源时抛出异常,true则使用默认数据源
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?Unicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mysql:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?Unicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
2、启动项目后,提示数据源找不到,报错 url 属性找不到
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (the profiles dev are currently active).
3、报错原因
SpringBoot 启动时自动配置数据库信息导致。
因为 DruidDataSourceAutoConfigure 在 DynamicDataSourceAutoConfiguration 之前会注入一个 DataSourceWrapper,会在原生的 spring.datasource 下找 url,username,password 信息
4、解决方案
在启动类上排除掉自动配置类即可,如下:
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)