与Spring有更好的方式:使用
PropertyPlaceholderConfigurer类.
classpath:com/foo/jdbc.properties
class="org.apache.commons.dbcp.BasicDataSource">
当您在属性占位符中指定PropertiesPersister的子类时,Spring会加载jdbc.properties并使用该类解密该文件.也许像:
public class MyPropertyPersister extends DefaultPropertiesPersister
{
// ... initializing stuff...
public void load(Properties props, InputStream is) throws IOException
{
Cipher decrypter = getCipher();
InputStream cis = new CipherInputStream(is, decrypter);
super.load(props, cis);
}
public void load(Properties props, Reader reader) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(reader, baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
Cipher decrypter = getCipher();
InputStream cis = new CipherInputStream(bais, decrypter);
InputStreamReader realReader = new InputStreamReader(cis);
super.load(props, realReader);
}
public void loadFromXml(Properties props, InputStream is) throws IOException
{
Cipher decrypter = getCipher();
InputStream cis = new CipherInputStream(is, decrypter);
super.loadFromXml(props, cis);
}
private Cipher getCipher()
{
// return a Cipher to read the encrypted properties file
...
}
...
}
希望它有帮助.
编辑
如果您使用Jasypt,则不需要定义任何PropertiesPersister.从Jasypt documentation:
Jasypt provides an implementation of these configuration-related Spring classes which can read .properties files with encrypted values (like the ones managed by the EncryptableProperties class) and handle them transparently to the rest of the Spring application beans.
有了这个,你可以像这样定义jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/reportsdb
jdbc.username=reportsUser
jdbc.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
并且Spring配置可能是这样的
/WEB-INF/classes/jdbc.properties
class="org.apache.commons.dbcp.BasicDataSource">
这样,您可以在启动应用程序时将密码解密为环境变量中的隐藏属性,并在以后取消设置.