Background:
In some configurations such as the configuration file: database password, etc., just to be safe needs to be encrypted, but in the other program reads these configuration items when you need to get real value.
Solution:
extend Spring's PropertyPlaceholderConfigurer class overrides method convertProperty
import com.util.StringUtil;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.*;
public class MyPropertyPlaceHolder extends PropertyPlaceholderConfigurer {
//需要加密的配置项名称
private static Set<String> encryptPropList;
public Map<String, String> map = new HashMap<String, String>();
/**
* 获取配置文件
* @param props
*/
@Override
protected void convertProperties(Properties props) {
System.out.println("convertProperties执行。。。");
Set<String> set = props.stringPropertyNames();
for(String item : set) {
map.put(item, props.getProperty(item));
}
super.convertProperties(props);
}
/**
* 重新设置配置项的值
* @param propertyName
* @param propertyValue
* @return
*/
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if(encryptPropList.contains(propertyName)) {
//将解密后的配置项放入spring的配置类中
return StringUtil.decodeByBase64(propertyValue);
}
return super.convertProperty(propertyName, propertyValue);
}
public String getValue(String key) {
if(encryptPropList.contains(key)) {
return StringUtil.decodeByBase64(map.get(key));
}
return map.get(key);
}
public Set<String> getEncryptPropList() {
return encryptPropList;
}
public void setEncryptPropList(Set<String> encryptPropList) {
this.encryptPropList = encryptPropList;
}
}
Spring configuration:
<bean id="propertyConfigurer" class="com.entity.MyPropertyPlaceHolder">
<property name="locations">
<list>
<!-- 这里支持多种寻址方式:classpath和file -->
<value>classpath:com/entity/app.properties</value>
<!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
<!--<value>file:/opt/demo/config/demo-mq.properties</value>-->
<!--<value>file:/opt/demo/config/demo-remote.properties</value>-->
</list>
</property>
<property name="encryptPropList">
<set>
<value>aliasName</value>
<value>test</value>
</set>
</property>
</bean>
In this way, access to configuration items after the item is decrypted when configured in Spring. Of course, you need to encrypt the configuration item, and then injected into encryptPropList years.