gpt4 book ai didi

java - 如何使用注释在 Spring 4 中重新加载属性文件?

转载 作者:IT老高 更新时间:2023-10-28 13:56:48 25 4
gpt4 key购买 nike

我有一个简单的应用程序,我在其中使用多个属性文件来获取其他用户编辑的内容(网站链接等)。

我加载属性的类如下所示:

@Configuration
@PropertySource("classpath:salestipsWhitelist.properties")
public class SalestipsWhitelist {

@Autowired
Environment env;

public Environment getEnv() {
return env;
}

public void setEnv(Environment env) {
this.env = env;
}

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

一些属性文件:

UPS_MPP_M_L=True
UPS_MPP_M_M=True
UPS_MPP_M_MP=True
UPS_MPP_M_S=True

这工作正常,但如果我对属性文件进行更改,我必须重新加载应用程序以可视化所做的任何更改。

如果我将位置移动到磁盘而不是类路径,是否可以定期或手动重新加载?我不希望这在更改时自动完成,因为我想控制何时完成/更新。

最佳答案

这是一种享受。需要 Java 7、Apache commons 日志记录、Apache commons lang (v2.6) 和 Apache commons 配置:

package corejava.reloadTest;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

public class MyApplicationProperties {
private static PropertiesConfiguration configuration = null;

static {
try {
configuration = new PropertiesConfiguration("test.properties");
} catch (ConfigurationException e) {
e.printStackTrace();
}
configuration.setReloadingStrategy(new FileChangedReloadingStrategy());
}

public static synchronized String getProperty(final String key) {
return (String) configuration.getProperty(key);
}
}

并使用以下方法对其进行测试:

package corejava.reloadTest;

public class TestReloading {
public static void main(String[] args) {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(MyApplicationProperties.getProperty("key"));
}
}
}

更改 test.properties 时的输出是这样的(test.props 的原始内容是 key=value,后来在程序执行过程中更改为 key=value1):

value
value
value
value
value
Jan 17, 2015 2:05:26 PM org.apache.commons.configuration.PropertiesConfiguration reload
INFO: Reloading configuration. URL is file:/D:/tools/workspace /AutoReloadConfigUsingApacheCommons/resources/test.properties
value1
value1
value1

您也可以考虑官方 Spring 框架引用文档 Refreshable beans ,为此使用像 Groovy 这样的 DSL

关于java - 如何使用注释在 Spring 4 中重新加载属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150527/

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