java – 如何使用注释在Spring 4中重新加载属性文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何使用注释在Spring 4中重新加载属性文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2255字,纯文字阅读大概需要4分钟。
内容图文
![java – 如何使用注释在Spring 4中重新加载属性文件?](/upload/InfoBanner/zyjiaocheng/713/e24399d80b4e4d0897992f5abf5151e9.jpg)
我有一个简单的应用程序,我使用几个属性文件来获取其他用户编辑的内容(链接到网站等).
我加载属性的类看起来像这样:
@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 mid-program execution):
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中重新加载属性文件?全部内容,希望文章能够帮你解决java – 如何使用注释在Spring 4中重新加载属性文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。