Spring中PropertyPlaceholderConfigurer类的用法教程
我们都知道 PropertyPlaceholderConfigurer 是用来读取配置文件的。一般我们只需简单的配置它即可,很少有对它进行重新改造的。本文将列举一个例子,如何通过 PropertyPlaceholderConfigurer 来读取加解密的配置信息。
PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。
通常我的配置如下:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>
现在想一下,如果我们的配置文件中对某些属性进行了加密,这时再使用 PropertyPlaceholderConfigurer 读取配置文件我们想要加密前的内容该怎么办?
答案就是重写 PropertyPlaceholderConfigurer。除了数据库的配置信息我们放在配置文件,然后可以通过 druid 进行加解密。但是配置的邮箱信息呢?
这时重写它就显得很有必要。PropertyPlaceholderConfigurer起的作用就是将占位符指向的数据库配置信息放在bean中定义的工具。
下面来看一个通过 PropertyPlaceholderConfigurer读取加解密配置文件的案例:
package com.xttblog.plugin;
import com.zheng.common.util.AESUtil;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
//支持加密配置文件插件
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private String[] propertyNames = {
"master.jdbc.password",
"slave.jdbc.password",
"generator.jdbc.password",
"master.redis.password"
};
//解密指定propertyName的加密属性值
@Override
protected String convertProperty(String propertyName, String propertyValue) {
for (String p : propertyNames) {
if (p.equalsIgnoreCase(propertyName)) {
return AESUtil.AESDecode(propertyValue);
}
}
return super.convertProperty(propertyName, propertyValue);
}
}
我们只需重写 PropertyPlaceholderConfigurer 类的 convertProperty 方法即可,然后在该方法中实现解密工作。
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/04/21 09:34