我回答自己的问题可能很有趣。但我仍然只是想告诉其他可能遇到同样问题的人我的解决方案。
为简单起见,我使用了 BASE64Encoder 和 BASE64Decoder。稍后我将修改我的代码以使用安全/更好的加密/解密算法。
我使用以下代码对我的数据库密码(例如:我的情况为 root)进行了编码:
private String encode(String str) {
BASE64Encoder encoder = new BASE64Encoder();
str = new String(encoder.encodeBuffer(str.getBytes()));
return str;
}
并将编码后的密码放入我的database.properties文件中,如下所示:
before
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/myDB
db.username=root
db.password=root
after
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/myDB
db.username=root
db.password=cm9vdA== (Note: encoded 'root' by using BASE64Encoder)
现在我已经为 org.apache.commons.dbcp.BasicDataSource 编写了一个包装类
并重写 setPassword() 方法:
import java.io.IOException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.misc.BASE64Decoder;
public class MyCustomBasicDataSource extends BasicDataSource{
public CustomBasicDataSource() {
super();
}
public synchronized void setPassword(String encodedPassword){
this.password = decode(encodedPassword);
}
private String decode(String password) {
BASE64Decoder decoder = new BASE64Decoder();
String decodedPassword = null;
try {
decodedPassword = new String(decoder.decodeBuffer(password));
} catch (IOException e) {
e.printStackTrace();
}
return decodedPassword;
}
}
这样我就可以解码(BASE64Decoder)database.properties中提供的编码密码
并且还修改了 springApplicationContext.xml 文件中提到的我的 dataSource bean 的类属性。
<beans:bean id="dataSource" class="edu.config.db.datasource.custom.MyCustomBasicDataSource" destroy-method="close">
<beans:property name="driverClassName"><beans:value>${db.driverClassName}</beans:value></beans:property>
<beans:property name="url"><beans:value>${db.url}</beans:value></beans:property>
<beans:property name="username"><beans:value>${db.username}</beans:value></beans:property>
<beans:property name="password"><beans:value>${db.password}</beans:value></beans:property>
Thanks.