問題: 當我們使用如下語句加載.properties時:
ClassLoader classLoader = this.getClass().getClassLoader(); Properties prop = new Properties(); prop.load(classLoader.getResourceAsStream("/Application.properties"));
會發現修改了.properties后,即使重新執行,讀入的仍為修改前的參數。此問題的原因在於ClassLoader.getResourceAsStream讀入后,會將.properties保存在緩存中,重新執行時會從緩存中讀取,而不是再次讀取.properties文件。
解決:
Properties prop = new Properties();
InputStream is = new FileInputStream(絕對路徑);
prop.load(is);
此時,FileInputStream不會將.properties保存在緩存中,即可以解決此問題。但另外讓人困惑的 一個問題會產生,即絕對路徑,會導致程序的通用性不好。這個問題是由於ClassLoader.getResourceAsStream是直接尋找 classes下的文件,FileInputStream則需要用完整的絕對路徑。
完美解決:
Properties prop = new Properties(); String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); InputStream is = new FileInputStream(path + "/VoucherManagement.properties");
此時已無需給出.properties絕對路徑,實現動態加載。