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

问题描述:

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

在Spring 3.2中是这样的可能吗?

+1

看看这个:http://*.com/questions/13248066/how-to-reload-properties-用弹簧。一旦Spring已经加载了bean,我不知道它是否可以修改它们或者替换它们。 – 2013-03-07 15:09:06

在主类的独立弹簧的应用程序,你可以做这样的事情:

//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文件中的属性值。有了这个,你不需要重建应用程序,你可以改变它的值并重新启动应用程序

+1

这种方法的问题是每次在我的一个application.properties文件中进行更改时,我将不得不重新启动应用程序。我正在寻找的解决方案是 - 能够在运行时从application.properties文件刷新/重新加载新值,而无需重新启动应用程序。 – jsf 2013-03-07 15:45:43

+0

这可能有助于 - http://www.morgan-design.com/2012/08/reloadable-application-properties-with.html – 2013-03-07 15:53:36