spring加载property文件

以jdbc.properties为例

1.通过spring配置jdbc.propertes

	<description>property文件加载配置</description>

	<!-- 加载property文件配置 -->
	
	 <!-- 不加密时候使用 -->
        <!--<context:property-placeholder location="classpath:jdbc.properties"/>--> 
	
	<!-- 加密的时候使用 -->
	<bean
		class="com.silvery.core.spring.jdbc.EncryptablePropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<!-- 数据库配置文件 -->
				<value>classpath:property/jdbc.properties</value>
			</list>
		</property>
		<!-- 加密的字段 -->
		<property name="fields">
			<array>
				<value>default.jdbcUrl</value>
				<value>default.user</value>
				<value>default.password</value>
			</array>
		</property>
	</bean>

2.EncryptablePropertyPlaceholderConfigurer是自己定义的类,通过重写PropertyPlaceholderConfigurer的processProperties加载器方法,实现解密并重新设置属性值,做到偷梁换柱,在真正使用配置之前完成解密。

package com.silvery.core.spring.jdbc;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.silvery.security.encrypt.impl.DESEncoder;

/**
 * 重写PropertyPlaceholderConfigurer的processProperties方法
 * 
 * @author shadow
 *
 */

public class EncryptablePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

	private String[] fields;

	protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {
		try {
			Properties new_props = props;
			for (String field : fields) {
				Object obj = props.getProperty(field);
				if (obj != null && obj.toString().length() > 0) {
					// 解密属性值,并重新设置
					new_props.put(field, DESEncoder.decrypt(obj.toString(), DESEncoder.DEFAULT_KEY));
				}
			}
			super.processProperties(beanFactory, new_props);
		} catch (Exception e) {
			throw new BeanInitializationException(e.getMessage());
		}
	}

	public String[] getFields() {
		return fields;
	}

	public void setFields(String[] fields) {
		this.fields = fields;
	}

}
3.jdbc的配置文件(部分)
# ======================= 数据库配置信息 ==========================
# 驱动类型
default.driverClass = com.mysql.jdbc.Driver
# 数据库路径 jdbc:mysql://127.0.0.1:3306/lchyy
default.jdbcUrl = TQrbIZK42ebirgavLn0SBs3jxC835zYy2CeCt9Cq09/dj1J7plBmMQ==
# 账号 root
default.user = ATXpuutonSc=
# 密码 hjj
default.password = Wd9Hd22f404=


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zerlinda_Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值