springboot配置druid
时间: 2023-08-19 19:09:39 浏览: 134
SpringBoot开发案例之配置Druid数据库连接池的示例
对于配置Druid连接池的Spring Boot项目,你可以按照以下步骤进行操作:
1. 在pom.xml文件中添加Druid的依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
2. 在application.properties(或application.yml)文件中添加Druid配置项,例如:
```properties
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.filters=stat,wall,log4j
# Druid监控配置
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
```
3. 创建一个配置类(可选),用于自定义Druid数据源的一些属性,例如:
```java
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
```
以上步骤完成后,你就成功地配置了Druid连接池。你可以使用@Autowired注解将DruidDataSource注入到你的代码中,然后就可以使用它来获取数据库连接了。希望这对你有所帮助!如果有任何疑问,请随时提问。
阅读全文