目前在 spring 中加载 propertioes 文件中的数据库资源的时候通常使用以下方式 java
<context:property-placeholder location="classpath:jdbc.properties"/>
咱们可能会遇到数据库用户名和密码的加密需求,因此特意写一个博文来进行这样的讲解 spring
在 spring 中有这样一个方式 ProepertyPlaceholderConfigurer 方法 , 是用来加载上面配置文件方法的。咱们只须要继承并重写。其中的方法 convertProperty。源代码中这个方法的源码为数据库
protected void convertProperties(Properties props) {
Enumeration<?> propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
String convertedValue = convertProperty(propertyName, propertyValue);
if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
props.setProperty(propertyName, convertedValue);
}
}
}
protected String convertProperty(String propertyName, String propertyValue) {
return convertPropertyValue(propertyValue);
}
咱们只须要对 convertProperty 方法进行重写便可。进行用户名和密码的解密操做。ide
/**
* 重写PropertyPlaceholderConfigurer 方法 这个方法是加载
* <context:property-placeholder location="classpath:jdbc.properties"/>
*
* 从新其中的convertProperty 方法 在这个方法里面进行字符串的解密
*
*
* Created by abing on 2015/11/5.
*/
public class DescPropertyResourceConfigure extends PropertyPlaceholderConfigurer {
/**
* 返回解密之后文件类型
* @param propertyName
* @param propertyValue
* @return
*/
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if (isDescStr(propertyName)){
return CommonSecurity.decode(propertyValue);
}
return propertyValue;
}
/**
* 判断获取到的是否是指定的字段
*
* @param propertyName
* @return
*/
public static boolean isDescStr(String propertyName){
boolean b = false;
if (propertyName.indexOf(Constant.USERNAME) >= 0 ||
propertyName.indexOf(Constant.PASSWORD) >= 0){
b =true;
}
return b;
}
}
代码已经成功了。须要在 spring 的配置文件中进行配置。测试
配置有以下方式 加密
方式一 :spa
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure"
p:location="classpath:jdbc.properties"/>
方式二:.net
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
<property />
</bean>
方式三:code
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
<property >
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
配置完成之后便可进行测试。
来源链接:
https://my.oschina.net/u/1023341/blog/526620