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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值