1. idea使用spring 初始化工具初始化springboot项目(要选中web)
下一步,下一步
2. 在pom.xml中,引入Druid连接池依赖:
<dependency>
<groupId>com.github.drtrang</groupId>
<artifactId>druid-spring-boot2-starter</artifactId>
<version>1.1.10</version>
</dependency>
3. 添加jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/leyou
jdbc.username=root
jdbc.password=123
4. 新建JdbcProperties
,用来进行属性注入
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author john
* @date 2019/12/4 - 19:17
*/
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
private String url;
private String driverClassName;
private String username;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
5. 配置数据源
创建JdbcConfiguration类:
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @author john
* @date 2019/12/4 - 18:05
*/
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {
@Autowired
private JdbcProperties jdbcProperties;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbcProperties.getUrl());
dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
dataSource.setUsername(jdbcProperties.getUsername());
dataSource.setPassword(jdbcProperties.getPassword());
return dataSource;
}
}
配置结束