上個月,我們遇到了類似的情況,客戶端需要在運行時更新配置文件。 我們創建使用@Value
@Component
public class ConfigurationManagerComponent{
@Value("conf.username")
private String userName;
@Value("conf.email");
private String email;
/*
* All your attributes
*/
//getters and setters
public String getUserName(){
return this.userName;
}
public void setUserName(String userName){
// first set the value to this class (component)
this.userName=userName;
//second save this value in the properties file
//a specific method you have to implement
saveproperties("conf.username",userName);
}
/*
* Do like this for all your getters and setters
*/
}
然後,在任何時候,你需要獲得或保存特性,只是注入該組件並使用它的getter和setter
@Autowired
ConfigurationManagerComponent configComponent;
String myActualUserName=configComponent.getUserName();
中央Spring組件加載從文件中的所有屬性
所以你可以從你的控制器獲取你的所有數據,並將它們設置爲你的彈簧模型以填充網頁中的表單,並且在編輯後保存時,你總是可以使用你的配置組件的setter(更新類和屬性文件)。
這種方法不是一個標準,只是我們用來解決問題的一種解決方案,它現在給出了很好的結果。 你也可以檢查Apache公共配置Here其他解決方案.. 希望這會有所幫助。
對於您的應用程序,您可以在加載屬性文件後將更新的屬性存儲到Map/Dto,並且如果需要可以從那裏讀取它。當您使用屬性文件綁定表單時,您需要確保您正在更新map/dto和屬性。您只能在應用程序啓動期間使用@Value。在上下文加載後它不會有用。 – asg
嗨,我對你提出的想法感興趣。你能否有任何我可以涉及的材料或例子?提前致謝! –
請檢查此.. https://stackoverflow.com/questions/42179664/inject-all-keys-and-values-from-property-file-as-map-in-spring – asg