在项目中,属性配置文件中常常放了许多项目中的配置,比如用户名密码等等,如果我们直接将这些明文密码暴露在配置文件中是非常的不安全的,所以我们就需要将属性文件中的部分信息进行加密处理以提高安全性。下面介绍如何运用spring中的PropertyPlaceholderConfigurer类对加密的属性值进行处理。
查看源码我们发现PropertyPlaceholderConfigurer的继承关系是这样的:
在PropertyResourceConfigurer类中我们发现有一个convertProperties()方法是处理配置文件的属性和值的
该方法调用convertProperty()方法,在convertProperty()方法中我们可以进行对密码进行解密,下面就开始实现:
package cn.e3mall.service.impl;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* @author sunqizheng
* @Title: PropertyPlaceholderConfigurerReal
* @ProjectName ttmall
* @Description: 自定义PropertyPlaceholderConfigurer类实现解密操作
* @date 2019/1/413:15
*/
public class PropertyPlaceholderConfigurerReal extends PropertyPlaceholderConfigurer {
//重写父类PropertyResourceConfigurer的convertProperty()方法
@Override
protected String convertProperty(String propertyName, String propertyValue) {
//如果属性配置文件的值含有redis.password就进行解密操作(这里简单处理)
if (propertyName.contains(PropertyConstant.REDIS_PASSWORD)){
propertyValue = propertyValue.substring(0,6);
System.out.println(propertyValue);
}
return this.convertPropertyValue(propertyValue);
}
}
如上图所示,我自定义了一个类实现PropertyPlaceholderConfigurer,并且重写其convertProperty()方法,这里为了简便我只是对redis的密码进行了解密,redis的加密规则也只是简单的密码后面增加两位,所以这里解密只需要截取前六位就行了
redis的属性配置文件:
PropertyConstant类:
package cn.e3mall.service.impl;
public class PropertyConstant {
public static final String REDIS_PASSWORD = "redis.password";
}
最后,我们在spring的配置文件中使用这个自定义的类来加载配置文件就行了,这时候就会进行对属性文件的解密操作
<bean id="propertyPlaceholderConfigurerReal" class="cn.e3mall.service.impl.PropertyPlaceholderConfigurerReal">
<property name="locations">
<list>
<value>classpath:conf/db.properties</value>
<value>classpath:conf/redis.properties</value>
<value>classpath:conf/resources.properties</value>
<value>classpath:conf/system.properties</value>
</list>
</property>
</bean>