1 项目新建
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springboot</groupId>
<artifactId>springboot-02</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
</project>
2 外部资源文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://127.0.0.1:3306/mall
3 读取外部资文件,配置连接池
package com.gp6.springboot02.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
@PropertySource(value = {"classpath:jdbc.properties"}, ignoreResourceNotFound = true)
public class PropertiesConfig {
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.password}")
private String jdbcPassword;
@Value("${jdbc.username}")
private String jdbcUserName;
@Value("${jdbc.driverClassName}")
private String jdbcDriverClassName;
@Bean(initMethod = "init",destroyMethod = "close")
public DruidDataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(jdbcUrl);
druidDataSource.setUsername(jdbcUserName);
druidDataSource.setPassword(jdbcPassword);
druidDataSource.setDriverClassName(jdbcDriverClassName);
return druidDataSource;
}
}