一般的开发,我们都习惯把数据库密码配置在属性文件中,这样配置方便好用,但是缺点也是很明显的。这样配置的密码是静态的、明文的。一般都安全要求比较严格的公司,这些密码都会被统一管理,定期修改。我们需要动态获取密码。下面是结合SpringBoot实现动态获取密码的一个简单例子:
首先是applicationContext.xml配置
<bean
id=
"dataSource" class=
"${spring.datasource.type}"
init-method=
"init" destroy-method=
"close">
<
property name=
"driverClassName" value=
"${spring.datasource.driver-class-name}" />
<
property name=
"url" value=
"${spring.datasource.url}" />
<
property name=
"username" value=
"${spring.datasource.username}" />
<
property name=
"password">
<bean
class=
"com.XXX.ide.iedp.common.PasswordFactory">
<
property name=
"safe" value=
"AIM_ICORE_CLAIM_IEDP" />
<
property name=
"folder" value=
"root" />
<
property name=
"object" value=
"iedpopr" />
<
property name=
"pwdProvider" ref=
"passwordProvider" />
</bean>
</
property>
<
property name=
"initialSize" value=
"${spring.datasource.initialSize}" />
<
property name=
"minIdle" value=
"${spring.datasource.minIdle}" />
<
property name=
"maxActive" value=
"${spring.datasource.maxActive}" />
<
property name=
"maxWait" value=
"${spring.datasource.maxWait}" />
<
property name=
"timeBetweenEvictionRunsMillis"
value=
"${spring.datasource.timeBetweenEvictionRunsMillis}" />
<
property name=
"minEvictableIdleTimeMillis"
value=
"${spring.datasource.minEvictableIdleTimeMillis}" />
<
property name=
"validationQuery" value=
"${spring.datasource.validationQuery}" />
<
property name=
"testWhileIdle" value=
"${spring.datasource.testWhileIdle}" />
<
property name=
"testOnBorrow" value=
"${spring.datasource.testOnBorrow}" />
<
property name=
"testOnReturn" value=
"${spring.datasource.testOnReturn}" />
<
property name=
"poolPreparedStatements" value=
"${spring.datasource.poolPreparedStatements}" />
<
property name=
"maxPoolPreparedStatementPerConnectionSize"
value=
"${spring.datasource.maxPoolPreparedStatementPerConnectionSize}" />
<
property name=
"filters" value=
"${spring.datasource.filters}" />
<
property name=
"connectionProperties" value=
"${spring.datasource.connectionProperties}" />
</bean>
<bean
id=
"passwordProvider" class=
"com.XXX.ide.iedp.common.PasswordProvider"
init-method=
"init">
<
property name=
"appId" value=
"${cyberark.appId}" />
<
property name=
"appKey" value=
"${cyberark.appKey}" />
<
property name=
"configPath" value=
"password.properties" />
<
property name=
"remoteUrl"
value=
"${cyberark.remoteUrl}" />
<
property name=
"SSLVerify" value=
"true" />
</bean>
接着是application.properties配置
jdbc
.url=jdbc:postgresql://
88。
88.88.88:
8888/iedp
jdbc
.username=******
cyberark
.appId=******
cyberark
.appKey=******
cyberark
.remoteUrl=https:/getPassword
最后是获取密码的类与方法
这部分代码就不贴上来,其实主要的逻辑就有一个密码管理的统一接口,该接口接收跟数据库密码相关的参数,返回密码。主要实现是在PasswordProvider类中init方法里实现的。 该方法在applicationContext.xml配置启动druid连接池时,启动获取密码。