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

Java Spring如何在运行时从application.properties重新加载值,java,spring,spring-mvc,dependency-injection,Java,Spring,Spring Mvc,Dependency Injection,在Spring应用程序中,我从应用程序外部加载application.properties文件,例如/user/home/properties/application.properties。文件中的值通过bean中的@Value注释注入。我的新要求是能够更改application.properties文件中的值,并在bean中重新加载(或重新注入)新值 在Spring 3.2中是否可以这样做?在主类中的独立Spring应用程序上,您可以执行以下操作: //load the appcontext

在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();

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

查看以下内容:。一旦Spring加载了bean,我不知道它是否可以修改或替换它们。你应该使用refereshScope:如果你使用
@Configuration Properties
,你至少应该能够“手动”完成它,ie对从文件中读取的字段使用setter。这种方法的问题是每次更改application.properties文件时,我都必须重新启动应用程序。我正在寻找的解决方案是-能够在运行时刷新/重新加载application.properties文件中的新值,而无需重新启动应用程序。这可能会有所帮助-