spring xml读取Properties文件中的加密字段

来源:互联网 发布:网络运维与管理pdf 编辑:程序博客网 时间:2024/05/18 19:40

spring的xml配置文件,能够方便地读取properties文件中的值。

读取单个属性文件:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:password.properties"/></bean>


读取多个属性文件:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:a1.properties</value><value>classpath:a2.properties</value></list></property></bean>

不过spring自带的PropertyPlaceholderConfigurer是将属性文件中的值原样读出。实际上一般的密码等敏感信息,项目中都会进行加密存储。也就是说properties中存储的是加密后的结果,这样必需解密后才能使用。


我们可以继承PropertyPlaceholderConfigurer来实现解密:

package net.aty.spring.ioc.password;import java.util.List;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;public class EncryptPropertyPlaceholderConfigurer extendsPropertyPlaceholderConfigurer {private List<String> encryptPropNames;@Overrideprotected String convertProperty(String propertyName, String propertyValue) {if (encryptPropNames.contains(propertyName)) {return DESUtil.decrypt(propertyValue);}return super.convertProperty(propertyName, propertyValue);}public List<String> getEncryptPropNames() {return encryptPropNames;}public void setEncryptPropNames(List<String> encryptPropNames) {this.encryptPropNames = encryptPropNames;}}
package net.aty.spring.ioc.password;import java.io.UnsupportedEncodingException;import org.springframework.util.Base64Utils;public class DESUtil {public static String encrypt(String src) {try {return Base64Utils.encodeToString(src.getBytes("UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}public static String decrypt(String src) {try {return new String(Base64Utils.decodeFromString(src), "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}public static void main(String[] args) {System.out.println(encrypt("aty"));System.out.println(encrypt("123456"));}}

对应的properties文件如下:
userName = atypassword = 123456userName.after.encrypt=YXR5password.after.encrypt=MTIzNDU2


spring配置文件如下:
<bean class="net.aty.spring.ioc.password.EncryptPropertyPlaceholderConfigurer"><property name="encryptPropNames"><list><value>userName.after.encrypt</value><value>password.after.encrypt</value></list></property><property name="locations"><list><value>classpath:password.properties</value></list></property></bean><bean id="atyBean" class="net.aty.spring.ioc.password.ShowPasswordBean"><property name="name" value="${userName.after.encrypt}" /><property name="password" value="${password.after.encrypt}" /></bean>


如此即可实现解密:



1 0