需求:因项目需要将数据库连接账号密码需要加密处理。
首先,先贴出加密前配置等信息
1、加密前的数据库连接账号、密码
2、配置文件
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
其次,这是加密的处理
1、加密后的数据库连接账号、密码
2、修改配置文件信息
<context:property-placeholder location="classpath:db.properties"/>
<!-- 上面的修改为下方代码 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="propertyConfigurer"
class="com.dp.core.common.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<!-- 这部分不变 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
3、新建EncryptPropertyPlaceholderConfigurer继承PropertyPlaceholderConfigurer,获取Properties对象,并将对象中的数据库账号、密码解密set(数据库账号密码的加、解密可以找其他的加密工具类加密,这里使用的是DES)
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class EncryptPropertyPlaceholderConfigurer extends
PropertyPlaceholderConfigurer {
private String[] encryptPropNames = { "jdbc.username", "jdbc.password" };
@Override
protected void processProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props) throws BeansException {
DesUtils des;
try {
//加解密
des = new DesUtils("222");
for (String encryptName : encryptPropNames) {
String name = props.getProperty(encryptName);
if (null != name) {
// 将加密的username和password解密后塞到props
props.setProperty(encryptName, des.decrypt(name));
}
}
super.processProperties(beanFactoryToProcess, props);
} catch (Exception e) {
e.printStackTrace();
}
}
}