JAVA:spring數據源中使用加密的用戶名和密碼


步驟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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM