why?
連接信息暴露在配置文件中有風險
how?
一、准備加密后連接信息
使用Druid自帶工具類ConfigTools加密連接信息

import com.alibaba.druid.filter.config.ConfigTools; public class DecryptDruid { public DecryptDruid() { super(); // TODO Auto-generated constructor stub } public static void main(String[] args){ DecryptDruid dp = new DecryptDruid(); String[] myUserPass ={url,driverclassname,username,password}; for(int i = 0;i < myUserPass.length();i++){ dp.testDecrypt(dp.testEncrypt(myUserPass)); } } /** * 對文字進行解密 * @throws Exception */ public String testDecrypt(String encry){ //解密 String word=encry; String decryptword=""; try { decryptword = ConfigTools.decrypt(word); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } System.out.println(decryptword); return decryptword; } /** * 文字進行加密 * @throws Exception */ public String testEncrypt(String userpass) { //加密 String encryptword = ""; try { encryptword = ConfigTools.encrypt(userpass); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } System.out.println(encryptword); return encryptword; } }
二、准備解密方法類
繼承DruidDataSource,覆蓋父類連接信息set方法

import com.alibaba.druid.filter.config.ConfigTools; import com.alibaba.druid.pool.DruidDataSource; @SuppressWarnings("serial") public class EncryptDruidDataSource extends DruidDataSource{ @Override public void setUrl(String url){ try { url = ConfigTools.decrypt(url); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } super.setUrl(url); } @Override public void setDriverClassName(String driverClassName){ try { driverClassName = ConfigTools.decrypt(driverClassName); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } super.setDriverClassName(driverClassName); } @Override public void setUsername(String username){ try { username = ConfigTools.decrypt(username); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } super.setUsername(username); } @Override public void setPassword(String password){ try { password = ConfigTools.decrypt(password); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } super.setPassword(password); } }
三、更改配置文件
將加密后連接信息加入配置文件
filters=config
四、更改dataSource配置
<bean id="dataSource" class="com.**.**.EncryptDruidDataSource" destroy-method="close">
添加:
<property name="connectionProperties" value="config.decrypt=true;" />
OK!
不過,配置mybatis會有databaseid not found問題,如有解決者,望賜教!