spring--给配置文件.properties加密

11111111111编写类并继承PropertyPlaceholderConfigurer.java

package com.xx.encryptDecrypt;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.xx.core.encrypt.EncryptUtil;

/**
* <br>
* Title:PropertyPlaceholderConfigurerExt <br>
* Description:PropertyPlaceholderConfigurer扩展
*/
public class PropertyPlaceholderConfigurerExt extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertyMap;
private static Logger log = Logger.getLogger(PropertyPlaceholderConfigurerExt.class);
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
propertyMap = new HashMap<String, String>();
String encryptNames = props.getProperty("encryptNames");
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);

if (encryptNames.contains(keyStr)) {
try {
props.setProperty(keyStr, EncryptUtil.decrypt(value));
propertyMap.put(keyStr, EncryptUtil.decrypt(value));
} catch (Exception e) {
e.printStackTrace();
log.info("解密出错,配置文件的密文可能有误!!!!!!!!!1");
}
} else {
propertyMap.put(keyStr, value);
}
}
System.out.println(propertyMap.toString());

super.processProperties(beanFactoryToProcess, props);
}

// 自定义一个方法,即根据key拿属性值,方便java代码中取属性值
public static String getProperty(String name) {
return propertyMap.get(name);
}
}

22222222222---spring上下文配置

<bean id="propertyConfigurer" class="com.ytd.encryptDecrypt.PropertyPlaceholderConfigurerExt">
         <property name="location" value="classpath:/conf/app.properties"/>
</bean>

3333333333---app.properties文件

账号密码改为密文

jdbc.username=bcc5b4b5174967b7
jdbc.password=bcc5b4b5174967b7

并添加键值对,作为解密标识

encryptNames=jdbc.username,jdbc.password

4444444444加密工具EncryptUtil.java不在贴出

猜你喜欢

转载自www.cnblogs.com/rdchen/p/10730257.html
今日推荐