首先创建一个JAVA类,来读取properties文件的需要解密的属性,加密解密使用的AES工具可以直接搜到,做成一个工具类,然后再调用。
DBPropertyPlaceholderConfigurer.java
public class DBPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private String[] encryptedProperties; // 需要解密的属key
public Properties getProperties() {
return properties;
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
private Properties properties; // 配置文件
public void setEncryptedProperties(String[] encryptedProperties) {
this.encryptedProperties = encryptedProperties;
}
@Override
protected void convertProperties(Properties properties) {
if(encryptedProperties != null) {
// 遍历需要解密的key
for(int i=0; i < encryptedProperties.length; i++) {
String key = encryptedProperties[i];
if(properties.containsKey(key)) {
String value = properties.getProperty(key);
// 解密
value = AESUtil.decrypt(value);
// 重新赋值
properties.setProperty(key, value);
}
}
}
this.properties = properties;
super.convertProperties(properties);
}
}
然后在applicationContext.xml里面配置bean
<bean id="placeholderConfigurer"
class="com.callray.alarm.DBPropertyPlaceholderConfigurer" >
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations" value="classpath:jdbc.properties"></property>
<property name="encryptedProperties">
<array>
<value>jdbc.user</value>
<value>jdbc.password</value>
</array>
</property>
</bean>
最后建一个测试类来测试有没有解密成功
public static void main(String[] args)
{
ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
DBPropertyPlaceholderConfigurer bean=(DBPropertyPlaceholderConfigurer) ctx.getBean("placeholderConfigurer");
System.out.println( bean.getProperties().getProperty("jdbc.user"));
System.out.println( bean.getProperties().getProperty("jdbc.password"));
}
加密后的配置是这样的
jdbc.user=SnP8wWkIWtwGzjYsRVdSXQ== jdbc.password=WgmuiVeZRbergKncCPZvqg==
测试解密后
sa
123456
参考文章:spring项目中对jdbc.properties中的明文密码加密解密_jdbc密码加密_Mentality°的博客-优快云博客