1.pom.xml 增加
<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.3</version> </dependency>
2.配置 application.yml
spring: datasource: dynamic: druid: initial-size: 0 max-active: 8 min-idle: 2 max-wait: -1 min-evictable-idle-time-millis: 30000 max-evictable-idle-time-millis: 30000 time-between-eviction-runs-millis: 0 validation-query: select 1 validation-query-timeout: -1 test-on-borrow: false test-on-return: false test-while-idle: true pool-prepared-statements: true max-open-prepared-statements: 100 filters: stat,wall share-prepared-statements: true datasource: master: url: jdbc:mysql://localhost:3306/wuxianji?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 username: root password: root druid: initial-size: 5
3.修改 SpringBootApplication 注解配置
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
这样就可以使用动态数据源了。