以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=