springboot之配置数据源
程序员文章站
2022-05-24 16:10:56
...
配置数据源
关于springboot的数据库连接池,默认4种,tomcat自带,hikari,dbcp,dbcp2,按照顺序来。要指定某一个:
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
当然,前提是引入依赖。
<!-- 添加Tomcat-JDBC依赖 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<!-- 添加HikariCP依赖 -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<!-- 添加DBCP依赖 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<!-- 添加DBCP2依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
其实,tomcat—jdbc在引入spring-boot-start-jdbc时就引入了。
要使用第三方的数据源,引入依赖,添加type(上面的操作),定义数据源(在config配置类中添加@Bean),如:
@Configuration
public class DataSourceConfig {
@Autowired
private Environment env;
@Bean
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
}
也可以加上用@ConfigurationProperties(prefix = “spring.datasource.druid”):
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSource2Config {
private String url;
private String username;
private String password;
@Bean
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);// 用户名
dataSource.setPassword(password);// 密码
return dataSource;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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;
}
}
以上详解:https://blog.csdn.net/pengjunlee/article/details/80081231