spring--为web.properties密码加密,防止明文显示

今天碰到一个问题弄了很久,先说明一下情况,要求web.properties文件中password文件用密文方式存储。如下图:
spring--为web.properties密码加密,防止明文显示_第1张图片
但是直接改成密文是肯定登录 不上的,在spring-servlet.xml 配置

 
	
		
			web.properties
		
	

spring 中这个PropertyPlaceholderConfigurer类就是读取web.properties配置文件中的信息的。所以想要实现这个功能,就需要重写这个类的processProperties方法,并将配置应用到自己的类上。
重新定义的类:EncryptablePropertyPlaceholderConfigurer,并重写processProperties方法,将密码解密,这样生成jdbc对象,链接数据库就可以成功啦。

package cn.mastercom.mtno.comm;

import cn.mastercom.mtno.util.DesUtil;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class EncryptablePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    private static final String KEY = "Chris   ";
    private static final String IV = "12345678";
    protected Logger log = Logger.getLogger(this.getClass());

    public EncryptablePropertyPlaceholderConfigurer() {
    }

    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) {
        try {
            Set keySet = props.keySet();
            String pwdencrypt = GlobalWebSetting.getProperty("pwdencrypt", "yes");
            Iterator var5 = keySet.iterator();

            while(var5.hasNext()) {
                Object keyObj = var5.next();
                String keyStr = (String)keyObj;
                if (keyStr.contains(".password") && "yes".equals(pwdencrypt)) {
                    String password = DesUtil.decrypt(props.getProperty(keyStr), "Chris   ", "12345678");
                    props.setProperty(keyStr, password);
                }
            }
        } catch (Exception var9) {
            this.log.info("processProperties   error:" + var9);
        }

        super.processProperties(beanFactory, props);
    }
}

 
  

最后别忘了,将spring-servlet.xml 文件中加载配置文件中的路径改成自己重写的那个类


	
		
			web.properties
		
	

后记
这个问题弄了我很久,虽然现在说出来很简单,但是项目中框架啊封装的东西,不了解的话真的很费时间,所以建议大家,如果公司用了框架,特别是那种公司自己写的框架,大家还是抽时间看看源代码,不然碰到问题真的很难排查问题。哎,踩过的坑

你可能感兴趣的:(spring-原理)