spring的PreferencesPlaceholderConfigurer类对数据库密码进行加密

来源:互联网 发布:军团要塞知乎 编辑:程序博客网 时间:2024/05/22 16:00

在项目中为了数据库的安全,常常会要求对数据库密码进行加密。我的数据库配置是jdbc.properties, 在spring环境中,推荐的方法是PreferencesPlaceholderConfigurer类对properties文件进行处理。

具体的实现方法如下(des加密):

1:数据库文件配置

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://192.168.0.27\:3306/parameter
username=root
password=P4eA8Ny/smw=
#定义初始连接数  
initialSize=0
#定义最大连接数 
maxActive=20
#定义最大空闲  
maxIdle=20
#定义最小空闲  
minIdle=1
#定义最长等待时间  
maxWait=60000

2:class实现类:

package com.util;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;


import com.jyt.api.encrypt.DESUtil;
import com.jyt.api.string.StringUtil;


/**
 * 数据库密码回调解密
 */
@SuppressWarnings("serial")
public class TestUtil extends PropertyPlaceholderConfigurer{
@Override  
    protected String convertProperty(String propertyName, String propertyValue){  
        //如果在加密属性名单中发现该属性  
if("password".equals(propertyName)){
if (!StringUtil.isEmpty(propertyValue)){  
           propertyValue = DESUtil.getDecryptString(propertyValue);  
      } 
}
        return propertyValue; 
    }  
      
}

3:xml文件配置:

<!-- 加载配置文件 -->
<bean class="com.util.TestUtil">
<property name="locations">  
       <list>  
           <value>classpath:jdbc.properties</value>
         
       </list>  
   </property>  
   <property name="ignoreUnresolvablePlaceholders" value="true" />   
</bean>
<import resource="classpath:spring-mybatis.xml"/>
上述就使得jdbc.properties文件在加载的时候进入com.util.TestUtil 类对数据库密码进行处理了!


0 0
原创粉丝点击