[英]Reloading Properties files when changed
我正在將屬性文件加載到一個類,然后在整個應用程序中使用該類來獲取它們。
public class PropertiesUtil extends PropertyPlaceholderConfigurer {
private static Map<String, String> properties = new HashMap<String, String>();
@Override
protected void loadProperties(final Properties props) throws IOException {
super.loadProperties(props);
for (final Object key : props.keySet()) {
properties.put((String) key, props.getProperty((String) key));
}
}
public String getProperty(final String name) {
return properties.get(name);
}
}
並在ApplicationContext.xml中
<bean id="propertiesUtil"
class="com.test.PropertiesUtil">
<property name="locations">
<list>
<value>classpath:test/test.properties</value>
</list>
</property>
</bean>
現在我想確保每當更改屬性文件時重新加載它。
我有一個監聽器類,它與tomcat服務器一起初始化。 我已經為文件觀察者編寫了以下邏輯
TimerTask task = new FileWatcher(new File("c:\\temp-reb\\config\\config.properties")) {
/*
* (non-Javadoc)
* @see com.belgacom.rosy.rebecca.utils.FileWatcher#onChange(java.io.File)
*/
@Override
protected void onChange(File file) {
loadServiceProperties(file);
loadMetadata();
}
};
Timer timer = new Timer();
timer.schedule(task, new Date(), Long.valueOf(properties.getProperty("properties.file.timer.schedule"))); // repeat the check every second
問題是
- FileWatcher需要運行路徑,我不想硬編碼
- 如何告訴spring調用屬性來顯式重新加載!
- FileWatcher需要運行路徑,我不想硬編碼
只需將相對路徑設置為相同項目文件夾中的資源目錄,您可以使用getResource()
方法獲取該路徑。 您還可以使用system屬性訪問user.dir
,這是使用工作目錄。
File f = new File(System.getProperty("user.dir")+ "/test.properties");
System.out.println(f.getAbsolutePath());
2.如何告訴spring調用屬性來顯式重新加載!
你現在這樣做的方式對我來說似乎沒問題。 可能還有其他方法,但我沒有看到上述過程中的任何缺陷。
這條蜿蜒的小路通往黑暗的地方。 每個定義的Spring實例化並維護對單例的引用。 因此,如果客戶端注入依賴項,保留它,並且應用程序上下文開始提供新bean,那么您將處於一個真正丑陋的狀態。 如果你不使用你的屬性作為bean屬性你應該沒問題,但混合它不是真正的方法。
如果有的話,我會嘗試通過重新加載屬性來限制受影響的bean數量並將它們放在特殊范圍內。 這樣,每當您的范圍發生變化時,您將獲得具有最新配置的新bean。 至少你將擁有一個已定義的屬性生命周期,並確切地知道你所面對的是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.