繁体   English   中英

如何在执行时配置Java配置属性?

[英]How to configure Java configuration properties at execution time?

我有一个标准的Java应用程序,该应用程序在启动时会读取配置属性,可以很好地工作。 但是,我想在执行时更新配置属性,而不必每次都编译代码。 我将如何去做。

例如代码:

Properties py = new Properties();
    InputStream ins;
    String prepName = "config.properties";

    ins = getClass().getClassLoader().getResourceAsStream(prepName);

    if (ins == null) {
        System.err.println("Couldn't find the file!");
        return "Error";
    }
    py.load(ins);

    String message = py.getProperty("msg");

资源/ config.properties

msg=testMessage

如果我想动态更改消息,该怎么办?

您可以使用setProperty(String key,String value)在运行时更改值。

py.setProperty("msg", "newValue");

Leo的注释中引用的WatchService看起来很有趣。 在Java 7之前的版本中,我通过使用Properties对象和一个工作线程来完成此工作,该线程每15秒(或大约15秒)检查一次文件修改时间戳。 如果文件的时间戳更改,请从文件系统重新加载Properties对象。

就像是:

Properties py = new Properties();
long lastModMillis = 0L;
long modMillis = file.lastModified() // to get the file modification time

if (modMillis != lastModMillis)
{
    // reload data
    FileInputStream fis = ... 
    py.clear();
    py.load(fis);
    lastModMillis = modMillis;
}

(不包括工作线程代码)

确保考虑如何同步,以便当工作线程在文件更改时重新加载对象时,尝试读取数据的线程不会发生冲突。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM