springboot3配置druid
时间: 2023-10-16 17:06:15 浏览: 177
好的,关于配置 Druid 数据源,你可以按照以下步骤进行:
1. 在 pom.xml 中添加 Druid 和 JDBC 驱动的依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2. 在 application.properties 或 application.yml 中配置数据源信息:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# Druid 连接池配置
druid:
initial-size: 5
min-idle: 5
max-active: 20
test-on-borrow: true
validation-query: SELECT 1 FROM DUAL
```
3. 在启动类上添加 @EnableTransactionManagement 注解开启事务管理,并在数据源配置类上添加 @ConfigurationProperties(prefix = "spring.datasource.druid") 注解将 Druid 的配置属性注入到数据源中。
```java
@SpringBootApplication
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidConfig {
private String url;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
// 省略 getter 和 setter 方法
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setInitialSize(initialSize);
dataSource.setMinIdle(minIdle);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(maxWait);
return dataSource;
}
}
```
阅读全文