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不在貼出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM