![](/img/trans.png)
[英]Junit test case for following json without giving direct values or hardcoding
[英]Giving database password without hardcoding it in the program
我們如何創建一個JDBC連接創建邏輯,該邏輯不需要在DB憑證發生更改時就更改Java代碼?
注意::數據庫的用戶名和密碼將由用戶 (具有特殊特權)提供...完全的權限授予他。
我的意思是,數據庫用戶名,密碼和其他詳細信息通常在Java程序中進行硬編碼。 還有什么其他方法可以保留它,以便在更改憑據時無需更改Java代碼? 我們還必須牢記憑證的隱私和安全因素 ...
像這樣:
Properties properties = new Properties();
properties .load(new FileInputStream(new File("c:\\credentials.properties")));
String user = properties.getProperty("username");
String pass = properties.getProperty("password");
//...
certificate.properties的內容如下所示:
#DB properties:
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost/mydatabase?useEncoding=true&characterEncoding=UTF-8
username = dit
password = 123456
您可以使用屬性文件來存儲所有憑據和數據庫URL。
您可以使用一些庫來允許您從XML文件加載配置-我更喜歡XStream 。 我的數據庫配置保存在配置XML中,更改憑據后,我唯一需要做的就是重新啟動應用程序。
為了提高安全性,您可以將解密密鑰硬編碼到應用程序中,然后將加密的密碼保存到配置文件中。
當我的應用程序啟動時,我將創建一個包含該應用程序所有配置的類:
public class ConfigurationUtils {
public static final Config config;
static {
XStream xstream = new XStream();
xstream.alias("config", Config.class);
xstream.alias("proxy", Proxy.class);
xstream.alias("database", Database.class);
xstream.alias("mailServer", MailServer.class);
// Check if a configuration file exists, otherwise use the config from the resources
File file = new File("/etc/applicationname/config.xml");
if(file.exists()) {
config = (Config) xstream.fromXML(file);
} else {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("config.xml");
config = (Config) xstream.fromXML(is);
}
}
}
引用的類是簡單的數據類,由與config.xml中的名稱匹配的私有屬性,getter和setter組成-XStream處理XML值到該類的映射。
如果您的程序是交互式程序,則會彈出一個對話框,其中可以包含用戶名和密碼。 如果是命令行程序,則可以在命令行上指定用戶名和密碼,並在“公共靜態void main(String [] args)”方法的“ args”變量中訪問這些值。 如果它是沒有用戶交互的批處理程序,則可以使用上面其他貢獻者提到的任何方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.