目前在spring中加载propertioes文件中的数据库资源的时候一般使用如下方式
<context:property-placeholder location="classpath:jdbc.properties"/>
我们可能会遇到数据库用户名和密码的加密需求,所以特地写一个博文来进行这样的讲解
在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方法进行重写即可。进行用户名和密码的解密操作。
/**
* 重写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的配置文件中进行配置。
配置有如下方式
方式一 :
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure"
p:location="classpath:jdbc.properties"/>
方式二:
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
<property name="location" value="classpath:jdbc.properties"/>
</bean>
方式三:
<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
配置完成以后即可进行测试。其中加解密的地方可以参考我的博文
http://my.oschina.net/u/1023341/blog/526601