依赖版本

依赖版本如下:
<properties> <java.version>1.8</java.version>
<spring-boot.version>2.6.11</spring-boot.version>
<druid-spring-boot-starter.version>1.2.5</druid-spring-boot-starter.version>
</properties>
替换但不自定义

一般情况下,我们只是替换spring boot默认的数据源为druid,这种情况下,配置文件如下:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url:
jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true username:
root password: 123456 type: com.alibaba.druid.pool.DruidDataSource druid:
initialSize: 10 minIdle: 1 maxActive: 20 maxWait: 60000
timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 testWhileIdle: true testOnBorrow: false testOnReturn:
false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize:
20 filters: stat,wall
这种配置是没有问题,相信这种写法在网上一搜都有很多,我们可以验证下,druid的配置是生效的。如下,启动的时候打印druid相关配置信息:

和我们配置文件中是一样,属性配置是成功注入生效的。

替换并自定义

使用druid的时候,我们可以自定义处理某些配置项,比如对数据库连接进行加密等操作。

如下,自定义一个数据源类:
public class CustomDatasource extends DruidDataSource { private final
DataSourceProperties properties; private final boolean unEncrypt; public
CustomDatasource(DataSourceProperties properties) { this.properties =
properties; String url = this.properties.getUrl(); unEncrypt =
url.contains("mysql") || url.contains("jdbc") || url.contains("localhost") ||
url.contains("127.0.0.1"); } @Override public void setPassword(String password)
{ super.setPassword(unEncrypt ? password : AESCoderUtil.decode(password)); }
@Override public void setUsername(String username) {
super.setUsername(unEncrypt ? username : AESCoderUtil.decode(username)); }
@Override public synchronized void setUrl(String url) { super.setUrl(unEncrypt
? url : AESCoderUtil.decode(url)); } }
托管spring容器:
@Configuration public class DatasourceConfiguration { @Bean
@ConfigurationProperties(prefix = "spring.datasource") public DataSource
getDataSource(DataSourceProperties properties) { DruidDataSource
druidDataSource = new CustomDatasource(properties); return druidDataSource; } }
查看druid的自动配置,可以看到自定义数据源的bean存在,druid便不再创建数据源bean:

 

 但是如果还以上面配置文件的方式配置druid的属性是不生效的,如下:

与配置文件的值不一致。

这是因为我们指定注入属性前缀是spring.datasource,所以修改配置如下:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url:
jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true username:
root password: 123456 type: com.alibaba.druid.pool.DruidDataSource # druid:
initialSize: 10 minIdle: 1 maxActive: 20 maxWait: 60000
timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 testWhileIdle: true testOnBorrow: false testOnReturn:
false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize:
20 filters: stat,wall
 注意看注释的地方,这样就可以了。

对于一个新手,如果只是通过网络搜索资料就进行配置,万一没有配置正确并且忽略这个细节,自己不进行验证是很难发现这个配置不生效的。

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信