我已經寫了PropertyUtils類(來自互聯網),這將載入屬性動態加載屬性文件中使用Spring
<bean id="propertiesUtil" class="com.myApp.PropertiesUtil" >
<property name="locations">
<list>
<value>classpath:myApp/myApp.properties</value>
</list>
</property>
</bean>
和PropertiesUtil類就像下面
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);
}
}
後來,我可以通過調用PropertiesUtil.getProperty()方法獲取該屬性。
但現在我想修改它稍有這樣,如果myApp.properties得到修改/用戶改變,應再次加載
也許我需要FileWatcher類
public abstract class FileWatcher extends TimerTask {
private long timeStamp;
private File file;
public FileWatcher(File file) {
this.file = file;
this.timeStamp = file.lastModified();
}
@Override
public final void run() {
long timeStampNew = this.file.lastModified();
if (this.timeStamp != timeStampNew) {
this.timeStamp = timeStampNew;
onChange(this.file);
}
}
protected abstract void onChange(File newFile);
}
但我懷疑是
- 我如何使用類路徑創建File對象:對myApp/myApp.properties (因爲絕對路徑是不知道)
- 如何調用/調用彈簧到 加載/將新的myApp.properties傳遞給PropetisUtil類[在 onChange方法中]。
在你的方法loadProperties()中,是否有任何特定的原因你循環每個屬性?你不能使用Properties作爲參數的Properties類的構造函數嗎? – Parvez