繁体   English   中英

Spring如何在运行时从application.properties重新加载值

[英]Spring how to reload the values from application.properties at runtime

在我的 Spring 应用程序中,我从应用程序外部加载application.properties文件,例如/user/home/properties/application.properties 文件中的值是通过 bean 中的 @Value 注解注入的。 我的新要求是能够更改application.properties文件中的值并重新加载(或重新注入)bean 中的新值。

在 Spring 3.2 中是否有可能发生这样的事情?

在主类中的独立 spring 应用程序上,您可以执行以下操作:

 //load the appcontext with refresh value as false
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                    new String[] { "classpath:appcontext.xml" }, false);
//add the props file
context.getEnvironment().getPropertySources().addFirst(new ResourcePropertySource("classpath:app.properties"));
//refresh the context
context.refresh();

这样做是使用在 appcontext.xml 文件中调用的所有属性中定义的属性加载 spring 上下文,但在加载时不会刷新。 然后它说首先加载app.properties 那时只考虑 app.properties 中的值。 然后刷新上下文。 现在 app.properties 文件中的属性值已加载。 有了这个,您不需要重建应用程序,您只需更改值并重新启动应用程序

应用程序上下文启动后,您无法重新加载 application.properties 中的属性,除非 java 进程已关闭并且您需要再次构建和运行。 理想的选择是使用会话或缓存或任何事件驱动的消息传递框架,如 Kafka。 这完全取决于您的要求和您能够使用的框架。

暂无
暂无

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

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