Since we are currently working on a project where a requirement is that all functions are loaded into the system in the form of plug-ins, it is necessary to use spring to dynamically load the configuration file under a certain location, so we summarize the way in which the XML configuration file is loaded in spring, and I summarize 6 kinds of XML is the most common spring application configuration source. Several containers in spring support the use of XML assembly beans, including:
Xmlbeanfactory,classpathxmlapplicationcontext,filesystemxmlapplicationcontext,xmlwebapplicationcontext
One: xmlbeanfactory reference Resources
Resource Resource = new Classpathresource ("Appcontext.xml");
Beanfactory factory = new Xmlbeanfactory (Resource);
Two: Classpathxmlapplicationcontext compilation path
ApplicationContext factory=new classpathxmlapplicationcontext ("Classpath:appcontext.xml");
In the SRC directory
ApplicationContext factory=new classpathxmlapplicationcontext ("Appcontext.xml");
ApplicationContext factory=new Classpathxmlapplicationcontext (new string[] {"Bean1.xml", "Bean2.xml"});
Under the src/conf directory
ApplicationContext factory=new classpathxmlapplicationcontext ("Conf/appcontext.xml");
ApplicationContext factory=new classpathxmlapplicationcontext ("File:g:/test/src/appcontext.xml");
Three: Using the file system path
ApplicationContext factory=new filesystemxmlapplicationcontext ("Src/appcontext.xml");
The classpath: prefix is used as a flag, so that Filesystemxmlapplicationcontext can also read the relative path in Classpath
ApplicationContext factory=new filesystemxmlapplicationcontext ("Classpath:appcontext.xml");
ApplicationContext factory=new filesystemxmlapplicationcontext ("File:g:/test/src/appcontext.xml");
ApplicationContext factory=new filesystemxmlapplicationcontext ("G:/test/src/appcontext.xml");
Four: Xmlwebapplicationcontext is specifically tailored for Web engineering.
ServletContext ServletContext = Request.getsession (). Getservletcontext ();
ApplicationContext CTX = Webapplicationcontextutils.getwebapplicationcontext (ServletContext);
V: Use beanfactory
Beandefinitionregistry reg = new Defaultlistablebeanfactory ();
Xmlbeandefinitionreader reader = new Xmlbeandefinitionreader (reg);
Reader.loadbeandefinitions (New Classpathresource ("Bean1.xml"));
Reader.loadbeandefinitions (New Classpathresource ("Bean2.xml"));
Beanfactory bf= (beanfactory) reg;
Spring six ways to load XML