gpt4 book ai didi

java - 使用 Spring 动态加载属性文件

转载 作者:搜寻专家 更新时间:2023-11-01 01:05:07 24 4
gpt4 key购买 nike

我写了一个 PropertyUtils 类(来自互联网),它将加载属性

<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);
}

但我的疑问是

  1. 如何使用类路径创建文件对象:myApp/myApp.properties(因为不知道绝对路径)
  2. 我如何调用/调用 spring 来加载/传递新的 myApp.properties 到 PropetisUtil 类 [inonChange 方法]。

最佳答案

以下支持您正在寻找的内容:

https://commons.apache.org/proper/commons-configuration/userguide/howto_properties.html

PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());

这应该可以解决问题。我自己没有使用过它,但它似乎非常简单。

关于java - 使用 Spring 动态加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com