检测Apache Commons Configuration2中的文件重新加载

使用org.apache.commons:commons-configuration2:2.1我的应用程序需要知道何时重新加载配置文件,以便它可以更新程序中的某些内容. Apache Commons Configuration2使用了很多策略和工厂,通常这很好,但是它变得如此复杂,我无法弄清楚我需要在哪里安装一个监听器.

该应用程序有这个:

configConfigurationBuilder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
    PropertiesConfiguration.class)
        .configure(new Parameters().properties().setFile(getConfigFile()));
final PeriodicReloadingTrigger configReloadingTrigger = new PeriodicReloadingTrigger(
    configConfigurationBuilder.getReloadingController(), null, 1, TimeUnit.MINUTES);
configReloadingTrigger.start();

我可以在哪些内容中安装一个监听器?我只是想在重新加载配置文件时收到通知.

我注意到ReloadingDetector接口有一个reloadingPerformed()方法,这听起来像我想要的.但是如何添加自己的ReloadingDetector?看起来ReloadingController只保留一个ReloadingDetector.当然,我没有子类ReloadingDetector并安装自定义的,是吗?我不想专门进行重新加载检测,因此子类化不合适 – 我只是想在事情发生时得到通知.此外,对于我来说,我甚至可以在ReloadingFileBasedConfigurationBuilder事件链中使用某些内部因子来创建检测器.

那么如何在重新加载配置时轻松让Apache Commons Configuration2通知我?

最佳答案 我把这个问题发给了
Apache Commons mailing list,Oliver Heger回答说:

You can add an event listener at the ReloadingController, then you
receive notifications of type ReloadingEvent.

Alternatively, you could also register a more generic listener for
events on the configuration builder itself. When the builder’s managed
configuration is reset, a corresponding event is produced. This also
happens during a reload operation.

起初我很困惑这些事件是在检测到需要重新加载时还是在重新加载后发出的,但他提醒我:

Maybe a misunderstanding of the reloading mechanism: New data is not
automatically pushed into a Configuration object you might have a
reference to. Rather, the configuration builder is reset. So the next
time you query the builder for a configuration you get a new one with
updated data.

When you receive one of the mentioned events the builder has been reset
and thus you know that new data is available.

这是一个有用的答案,我正在分享以帮助其他人. (我希望Apache Commons开发人员能够监控并在Stack Overflow上运行.)

点赞