背景:
このような構成ファイルなどの一部の構成では:データベースのパスワードなど、念のためには、暗号化する必要がありますが、実際の値を取得する必要がある場合、他のプログラムでこれらの設定項目を読み込みます。
ソリューション:
春のPropertyPlaceholderConfigurerクラスのオーバーライドメソッドconvertPropertyを拡張
import com.util.StringUtil;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.*;
public class MyPropertyPlaceHolder extends PropertyPlaceholderConfigurer {
//需要加密的配置项名称
private static Set<String> encryptPropList;
public Map<String, String> map = new HashMap<String, String>();
/**
* 获取配置文件
* @param props
*/
@Override
protected void convertProperties(Properties props) {
System.out.println("convertProperties执行。。。");
Set<String> set = props.stringPropertyNames();
for(String item : set) {
map.put(item, props.getProperty(item));
}
super.convertProperties(props);
}
/**
* 重新设置配置项的值
* @param propertyName
* @param propertyValue
* @return
*/
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if(encryptPropList.contains(propertyName)) {
//将解密后的配置项放入spring的配置类中
return StringUtil.decodeByBase64(propertyValue);
}
return super.convertProperty(propertyName, propertyValue);
}
public String getValue(String key) {
if(encryptPropList.contains(key)) {
return StringUtil.decodeByBase64(map.get(key));
}
return map.get(key);
}
public Set<String> getEncryptPropList() {
return encryptPropList;
}
public void setEncryptPropList(Set<String> encryptPropList) {
this.encryptPropList = encryptPropList;
}
}
Spring構成:
<bean id="propertyConfigurer" class="com.entity.MyPropertyPlaceHolder">
<property name="locations">
<list>
<!-- 这里支持多种寻址方式:classpath和file -->
<value>classpath:com/entity/app.properties</value>
<!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
<!--<value>file:/opt/demo/config/demo-mq.properties</value>-->
<!--<value>file:/opt/demo/config/demo-remote.properties</value>-->
</list>
</property>
<property name="encryptPropList">
<set>
<value>aliasName</value>
<value>test</value>
</set>
</property>
</bean>
春に設定されている場合、このように、アイテムの後にコンフィギュレーション項目へのアクセスが復号されます。もちろん、あなたが設定項目を暗号化する必要があり、その後、encryptPropList年に注入します。