数据库密码在Spring配置文件是加密的,如何在运行时再进行解密呢?

目前在 spring 中加载 propertioes 文件中的数据库资源的时候通常使用以下方式 java

<context:property-placeholder location="classpath:jdbc.properties"/>

咱们可能会遇到数据库用户名和密码的加密需求,因此特意写一个博文来进行这样的讲解 spring

在 spring 中有这样一个方式 ProepertyPlaceholderConfigurer 方法  , 是用来加载上面配置文件方法的。咱们只须要继承并重写。其中的方法 convertProperty。源代码中这个方法的源码为数据库

protected void convertProperties(Properties props) {
   Enumeration<?> propertyNames = props.propertyNames();
   while (propertyNames.hasMoreElements()) {
      String propertyName = (String) propertyNames.nextElement();
      String propertyValue = props.getProperty(propertyName);
      String convertedValue = convertProperty(propertyName, propertyValue);
      if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
         props.setProperty(propertyName, convertedValue);
      }
   }
}

protected String convertProperty(String propertyName, String propertyValue) {
   return convertPropertyValue(propertyValue);
}

咱们只须要对 convertProperty 方法进行重写便可。进行用户名和密码的解密操做。ide

/**
 * 重写PropertyPlaceholderConfigurer 方法 这个方法是加载
 *          <context:property-placeholder location="classpath:jdbc.properties"/>
 *
 * 从新其中的convertProperty 方法 在这个方法里面进行字符串的解密
 *
 *
 * Created by abing on 2015/11/5.
 */
public class DescPropertyResourceConfigure extends PropertyPlaceholderConfigurer {

    /**
     * 返回解密之后文件类型
     * @param propertyName
     * @param propertyValue
     * @return
     */
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (isDescStr(propertyName)){
            return CommonSecurity.decode(propertyValue);
        }

        return  propertyValue;
    }

    /**
     * 判断获取到的是否是指定的字段
     *
     * @param propertyName
     * @return
     */
    public static boolean isDescStr(String propertyName){
        boolean b = false;

        if (propertyName.indexOf(Constant.USERNAME) >= 0 ||
                propertyName.indexOf(Constant.PASSWORD) >= 0){
            b =true;
        }

        return b;
    }

}

代码已经成功了。须要在 spring 的配置文件中进行配置。测试

配置有以下方式 加密

方式一 :spa

<bean id="descPropertyResourceConfigure"  class="com.inga.utils.properties.DescPropertyResourceConfigure"
      p:location="classpath:jdbc.properties"/>

方式二:.net

<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
   <property />
</bean>

方式三:code

<bean id="descPropertyResourceConfigure" class="com.inga.utils.properties.DescPropertyResourceConfigure" >
  <property >
       <list>
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

配置完成之后便可进行测试。


来源链接:

https://my.oschina.net/u/1023341/blog/526620

39671ca578875b45ae1c7a8dd1a477e3.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值