druid连接progresql
时间: 2023-07-08 09:35:01 浏览: 89
下面是在Spring Boot项目中使用Druid连接PostgreSQL的配置示例:
1. 添加Maven依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.8</version>
</dependency>
```
2. 在application.properties文件中配置Druid和PostgreSQL的连接信息:
```properties
# 数据源配置
spring.datasource.url=jdbc:postgresql://localhost:5432/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.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.test-on-borrow=true
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
```
3. 在配置类中添加Druid的DataSource:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
```
4. 在需要使用数据库的类中注入DataSource:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private DataSource dataSource;
// ...
}
```
阅读全文