SPRING 数据库密码加密存储 在配置文件的两种方式 第一种


package com.spring.demo.utils;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    @Override
    protected String convertProperty(String propertyName, String propertyValue)
    {
        //如果在加密属性名单中发现该属性
        if (isEncryptProp(propertyName))
        {
            String decryptValue =AesUtils.decrypt(propertyValue,AesUtils.key);
            System.out.println(decryptValue);
            return decryptValue;
        }else {
            return propertyValue;
        }

    }

    private boolean isEncryptProp(String propertyName)
    {
       if (propertyName.startsWith("encrypt")){
           return true;
       }
        return false;
    }

    public  void setLocation(Resource location) {
        String locationStr = location.toString();
        if (locationStr == null || locationStr.equals("")){
            return;
        }
        int start = locationStr.indexOf("[");
        int end = locationStr.indexOf("]");
        if (start < 0 || end < 0 || end <= start+1){
            return;
        }
        String locStr = locationStr.substring(start+1,end);
        String[] paths = locStr.split(",");
        List<Resource> list = new ArrayList<>();
        for (int i = 0; i < paths.length; i++) {
            String loc = paths[i];
            if (loc == null || loc.equals("")){
                continue;
            }
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            //将加载多个绝对匹配的所有Resource
            //然后进行遍历模式匹配
            try {
                Resource[] resources=resolver.getResources(loc);
                list.addAll(Arrays.asList(resources));
            } catch (IOException e) {
                continue;
            }
        }
        this.setLocations(list.toArray(new Resource[list.size()]));

    }
}


<bean id="decryptPropertyPlaceholderConfigurer"
          class="com.spring.demo.utils.DecryptPropertyPlaceholderConfigurer"
          p:location="classpath*:*.properties,classpath*:loc/*.properties">
    </bean>


上一篇:Java锁优化


下一篇:Netty-ChannelHandler-ChannelPipeline