文章概要:数据源配置文件database.properties里面填写加密后的密文,程序读取配置文件的时候进行相应的解密操作后再注入使用。此功能主要用于生产环境。
使用的spring版本:4.2.5,配置采用一贯的作风javaConfig
首先在springmvc配置文件当中声明一个PropertyPlaceholderConfigurer类型的bean:
@Bean
public PropertyPlaceholderConfigurer datasourceProperties() {
PropertyEncrypt propertyEncrypt = new PropertyEncrypt();
propertyEncrypt.setLocations(new ClassPathResource("database.properties"));
return propertyEncrypt;
}
然后定义用于读取配置文件时解密的类继承于PropertyPlaceholderConfigurer:
import com.core.shared.StringUtils;
import com.core.shared.encrypt.PEncryptUtil;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.ArrayList;
import java.util.List;
public class PropertyEncrypt extends PropertyPlaceholderConfigurer {
private static final List<String> encryptKey = new ArrayList<>();
static {
encryptKey.add("master.jdbc.url");
encryptKey.add("master.jdbc.username");
encryptKey.add("master.jdbc.password");
encryptKey.add("slave.jdbc.url");
encryptKey.add("slave.jdbc.username");
encryptKey.add("slave.jdbc.password");
}
public void addEncryptKey(String key) {
if (StringUtils.isNotEmpty(key)) {
encryptKey.add(key);
}
}
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if (encryptKey.contains(propertyName)) {
propertyValue = PEncryptUtil.decrypt(propertyValue);
}
return propertyValue;
}
}
PEncryptUtil是自己定义的加密解密类,最后在使用的时候使用@Value注入:
@Value("${master.jdbc.driverClassName}")
private String masterDriverClassName;
@Value("${master.jdbc.url}")
private String masterUrl;
@Value("${master.jdbc.username}")
private String masterUsername;
@Value("${master.jdbc.password}")
private String masterPassword;
配置文件里直接用密文就好了:
master.jdbc.url=abc
master.jdbc.username=abc
master.jdbc.password=abc