如何使用Spring重新加载属性?

我在Spring 3中使用属性文件。当Spring初始化它的上下文时,它会加载属性文件并将其放在所有带有@Value注释的bean中。

我希望有可能更新文件中的某些属性,并在服务器上公开JMX,将新属性重新加载到Spring – 无需重新启动服务器,并重新加载其上下文。

我可以通过使用一些Spring方法重新加载属性并将它们填充到所有bean来实现这一点,还是应该由我自己编写这样的东西?

我建议用Apache Commons Configuration项目java.util.PropertiesPropertiesConfiguration替换java.util.Properties 。 它支持自动重新加载,通过检测文件何时更改,或通过JMX触发。

我认为没有共同的方法。 最“干净”的是关闭Spring上下文并从头开始构建它。 例如,考虑使用DBCP连接池并更新其数据库连接URL。 这意味着必须正确关闭池,然后必须创建新对象,然后还必须更新对池的所有引用。 现在,一些bean可能从该池获取连接,并且更新池配置意味着您需要以某种方式重新请求连接。 因此,bean可能需要知道如何做到这一点,这是不常见的。

我建议使用配置和更新事件创建单独的bean,并将该bean作为依赖关系,以便了解有关配置更改的所有bean。 然后,您可以使用Apache Commons Configuration来获取文件更改并传播配置更新。

也许使用JMS是好的(如果你以后要分发你的应用程序)。

是的,你可以用Spring JMX方式做到这一点。 将这些bean添加到spring配置文件中。 创建一个单独的方法来读取属性文件。 在此示例中,我使用callThisAgain()方法。

           callThisAgain              

之后,您可以使用jconsole重新加载方法,而无需重新启动服务器。

使用与spring相同的apache如下:

 @Component public class ApplicationProperties { private PropertiesConfiguration configuration; @PostConstruct private void init() { try { String filePath = "/opt/files/myproperties.properties"; System.out.println("Loading the properties file: " + filePath); configuration = new PropertiesConfiguration(filePath); //Create new FileChangedReloadingStrategy to reload the properties file based on the given time interval FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy(); fileChangedReloadingStrategy.setRefreshDelay(60*1000); configuration.setReloadingStrategy(fileChangedReloadingStrategy); } catch (ConfigurationException e) { e.printStackTrace(); } } public String getProperty(String key) { return (String) configuration.getProperty(key); } public void setProperty(String key, Object value) { configuration.setProperty(key, value); } public void save() { try { configuration.save(); } catch (ConfigurationException e) { e.printStackTrace(); } } } 

Apache为我们提供了使用可重载属性文件的实用程序。

         

虽然这里的一些人建议使用外部方式来使用属性(在Spring自己使用属性文件的方式之外)。 这个答案正是您在Spring Boot和Java EE中寻找的热门重新加载属性的https://stackoverflow.com/a/52648630/39998 。