在我的 Spring 应用程序中,我从应用程序外部加载 application.properties
文件,例如/user/home/properties/application.properties
。文件中的值通过 bean 中的 @Value 注释注入(inject)。我的新要求是能够更改 application.properties
文件中的值并重新加载(或重新注入(inject))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 文件中的属性值。有了这个,您不需要重建应用程序,您只需更改值并重新启动应用程序即可
关于java - Spring 如何在运行时从 application.properties 重新加载值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15274547/