posts - 91,  comments - 2,  views - 11万

步骤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   le.li  阅读(1183)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2019-02-03 JAVA:简单添加菜单界面(swing)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示