Encrypted configuration file configuration items

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.
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
    protected void convertProperties(Properties props) {
        Set<String> set = props.stringPropertyNames();
        for(String item : set) {
            map.put(item, props.getProperty(item));

     * 重新设置配置项的值
     * @param propertyName
     * @param propertyValue
     * @return
    protected String convertProperty(String propertyName, String propertyValue) {
        if(encryptPropList.contains(propertyName)) {
            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">
            <!-- 这里支持多种寻址方式:classpath和file -->
            <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
    <property name="encryptPropList">

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.

Guess you like

Origin www.cnblogs.com/binary-tree/p/10962948.html