简体   繁体   English

重新加载春季豆(不包括某些豆)

[英]Reload spring beans excluding some beans

I would like to have the ability to periodically check some properties file and apply changes in my app accordingly. 我希望能够定期检查一些属性文件,并相应地在我的应用程序中应用更改。

In my java-spring application I'm checking periodically whether the properties file loaded from the file-system has changed: 在我的java-spring应用程序中,我定期检查从文件系统加载的属性文件是否已更改:

Resource propsResource = new FileSystemResource("/path/to/properties/file");
File propertiesFile = propsResource.getFile();
long currentTimeStamp = propertiesFile.lastModified();
if (currentTimeStamp != lastModified) {
//File Changed
}

In case it has changed I would like to reload my spring beans since some of them are actually loaded conditionally relaying on the properties values in the properties file. 万一发生变化,我想重新加载我的spring bean,因为其中一些实际上是有条件地根据属性文件中的属性值加载的。

Using the refresh method did not do the trick so I'm actually calling the close method and recreating my context: 使用refresh方法并不能解决问题,因此我实际上是在调用close方法并重新创建上下文:

context.close();
context = new AnnotationConfigApplicationContext(AppConfig.class);

This does the trick. 这可以解决问题。 My problem is that I have some beans that contain cached data and I don't want to lose this data. 我的问题是我有一些包含缓存数据的bean,并且我不想丢失这些数据。 One solution is to keep using this method but make sure my cached data resides in classes that are not managed by spring (either static or singletones managed by me). 一种解决方案是继续使用此方法,但要确保我的缓存数据位于不受spring管理的类(由我管理的静态或单调)中。

Another solution could be to copy my cached data before recreating the context and then set it back to the newly create beans (those that hold the cached data) but this feels super ugly. 另一个解决方案可能是在重新创建上下文之前复制我的缓存数据,然后将其设置回新创建的Bean(用于保存缓存数据的Bean),但这感觉非常丑陋。

Is there a better approach for this? 有更好的方法吗?

i would rather not just reloading the Context files on your own, let the jvm take care of it. 我宁愿不只是自己重新加载Context文件,让jvm来处理它。

For the problem which you are facing, you might want to check out the Watcher service provided within Jdk 1.7 and above. 对于您面临的问题,您可能需要检查Jdk 1.7及更高版本中提供的Watcher服务。 What it does is, it checks if the files in a particular directory are modified, if it is modified you can override the method to do the things you wanted to do. 它的作用是检查特定目录中的文件是否被修改,如果被修改,您可以覆盖该方法来执行您想做的事情。

Watcher service in jdk 1.7 JDK 1.7中的Watcher服务

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

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