Well, it may be useful to perform such a context reload when testing your application.
You can try the refresh method of one of the AbstractRefreshableApplicationContext classes: it will not update your previously installed beans, but the next context call will return the updated beans.
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.springframework.context.support.FileSystemXmlApplicationContext; public class ReloadSpringContext { final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\"\n" + " \t\"http://www.springframework.org/dtd/spring-beans.dtd\">\n"; final static String contextA = "<beans><bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextA\"/>\n" + "</bean></beans>"; final static String contextB = "<beans><bean id=\"test\" class=\"java.lang.String\">\n" + "\t\t<constructor-arg value=\"fromContextB\"/>\n" + "</bean></beans>"; public static void main(String[] args) throws IOException { //create a single context file final File contextFile = File.createTempFile("testSpringContext", ".xml"); //write the first context into it FileUtils.writeStringToFile(contextFile, header + contextA); //create a spring context FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( new String[]{contextFile.getPath()} ); //echo the bean 'test' on stdout System.out.println(context.getBean("test")); //write the second context into it FileUtils.writeStringToFile(contextFile, header + contextB); //refresh the context context.refresh(); //echo the bean 'test' on stdout System.out.println(context.getBean("test")); } }
And you will get this result
fromContextA fromContextB
Another way to achieve this (and possibly simpler) is to use the Refreshable Bean Spring 2.5+ function With a dynamic language (groovy, etc.) And Spring you can even change the Bean behavior. Take a look at the spring link for a dynamic language :
24.3.1.2. Updated beans
One of (if not the most) irresistible incremental values โโof dynamic language support in Spring is the 'refreshable bean'.
The updated Bean is with support for the dynamic Bean language, which with a small configuration, with support for the dynamic Bean language, track changes to the source file resource, and then reload when the dynamic language changes the source file (for example, when the developer edits and saves the changes in the file to the File system).
Guillaume Jan 22 '10 at 9:24 2010-01-22 09:24
source share