为了更好地对数据库连接进行管理,我们引入数据库连接池。本例代码中采用阿里巴巴的Druid数据库连接池。
pom.xml文件引入:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
application.properties中添加数据库配置信息:
localhost.datasource.url = jdbc:postgresql://localhost:5432/postgres
localhost.datasource.username =
localhost.datasource.password =
localhost.datasource.driverClassName = org.postgresql.Driver
新建DataSourceProperties用于读取application.properties中的数据:
@Data
@ConfigurationProperties(prefix = "localhost.datasource")
public class DataSourceProperties {
private String url;
private String username;
private String password;
private String driverClassName;
}
@Data 为lombok注解,用于生成成员的getter,setter方法。
新建DataSourceConfig用于配置Druid连接池:
@Configuration
@EnableConfigurationProperties(D