步骤1、jdbc.properties文件中配置用户名、密码等

jdbc.url=jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=xxxx
jdbc.password=yyyy

 步骤2、spring.xml中配置资源文件

方法一,使用明文用户名和密码时,直接配置文件位置:

spring.xml

    <!-- 引入属性文件,jdbc.properties位于src/main/resources目录下 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

 方法二,spring中配置并添加一个类继承PropertyPlaceholderConfigurer实现使用加密字符串,使用时解密

spring.xml

    <bean id="encryptPropertyPlaceholderConfigurer" class="xxx.yyy.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean> 

 EncryptPropertyPlaceholderConfigurer.java

package xxx;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 继承自spring的PropertyPlaceholderConfigurer来扩展
 * 
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    
    /** 需要解密的字段 */
    private String[] encryptPropNames = { "jdbc.username", "jdbc.password" };

    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)) {
            // 解密(根据实际内容改成具体解密方法)
            return Util.xxxx(propertyValue);
        } else {
            return propertyValue;
        }
    }

    /**
     * 判断属性是否需要解密
     * 
     * @param propertyName
     * @return
     */
    @SuppressWarnings("deprecation")
    private boolean isEncryptProp(String propertyName) {
        for (String encryptpropertyName : encryptPropNames) {
            if (ObjectUtils.equals(encryptpropertyName, propertyName)) {
                return true;
            }
        }
        return false;
    }
}

 

posted on 2020-02-03 15:58  le.li  阅读(1126)  评论(0编辑  收藏  举报