公司一个项目的从另外一个小公司,拷贝了一个PropertyParser的类,实现的有问题,必须重启java应用才能读取新的配置。
简单的解决办法,就是每次读任何配置项时,都重新加载xxx.property文件,但是明显不如当年C#的ConfigurationManager好用。
https://stackoverflow.com/questions/20661612/java-equivalent-for-cs-configurationmanager-appsettingsx
这篇文章,只回答了web的,没有针对desktop和console类型的解答。
http://blog.163.com/s_zhchluo/blog/static/15014708200732191454527/
这篇文章提到了 Apache Commons Configuration项目,也解释了其功能原理,很符合我的要求。
https://commons.apache.org/proper/commons-configuration/
The Commons Configuration software library provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources.
望文生义,就是通用的配置库,很不错。
http://commons.apache.org/proper/commons-configuration/userguide_v1.10/howto_filebased.html
节选Automatic Reloading部分的说明:
Automatic Reloading
A common issue with file-based configurations is to handle the reloading of the data file when it changes. This is especially important if you have long running applications and do not want to restart them when a configuration file was updated. Commons Configuration has the concept of so called reloading strategies that can be associated with a file-based configuration. Such a strategy monitors a configuration file and is able to detect changes. A default reloading strategy is FileChangedReloadingStrategy. It can be set on a file-based configuration as follows:
PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");config.setReloadingStrategy(new FileChangedReloadingStrategy());
FileChangedReloadingStrategy works as follows: On every property access the configuration checks its associated reloading strategy. FileChangedReloadingStrategy will then obtain the last modification date of the configuration file and check whether it has changed since the last access. If this is the case, a reload is triggered. To avoid often disk access when multiple properties are queried from the configuration, a refresh delay can be set on the reloading strategy. This is a time in milli seconds with the meaning that the reloading strategy will only once check the file‘s last modification time in the period specified here.
每一次属性访问时,都会检查文件,如果最后访问时间有变化,则自动重新载入。为了减少硬盘访问频率,又添加了"刷新延迟(设定刷新延迟时间)"机制。上述机制基于commons-configuration/userguide_v1.10。
还有一篇介绍如何实现重载机制的文章,讲解了其他重载机制。
https://commons.apache.org/proper/commons-configuration/userguide/howto_reloading.html