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

时间:2013-03-07 15:04:53

标签: java spring spring-mvc dependency-injection

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

在Spring 3.2中是否可以这样?

1 个答案:

答案 0 :(得分:0)

在主类中的独立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文件中的属性值。使用此功能,您无需重建应用程序,只需更改值并重新启动应用程序

即可