Web project:
Method 1:
ApplicationContext AC1 = webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC)
Method 2:
ApplicationContext AC2 = webapplicationcontextutils.getwebapplicationcontext (ServletContext SC)
Method 3:
Write a tool class inheritance Applicationobjectsupport
Method 4:
Write a tool class inheritance Webapplicationobjectsupport
Method 5: (recommended)
Write a tool class to implement the Applicationcontextaware interface
Example:
Import Java.util.map;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import org.springframework.context.applicationcontextaware;/** * Tool class for getting applicationcontext and Object * @author Yzl * */@SuppressWarnings ({"Rawtypes", "Unchecked"}) public class Springcontextutils implements Applicationcontextaware {private static ApplicationContext Applicationcontext;public void Setapplicationcontext (ApplicationContext arg0) throws beansexception {applicationcontext = arg0;} /** * Get ApplicationContext Object * @return */public static ApplicationContext Getapplicationcontext () {return ApplicationContext;} /** * Find object based on Bean ID * @param ID * @return */public static object Getbeanbyid (String ID) {return applicationcontext.getbean (ID);} /** * finds objects based on the Bean's Class * @param c * @return */public static object Getbeanbyclass (Class C) {return APPLICATIONCONTEXT.GETB EAN (c);} /** * finds all objects (including subclasses) according to the Bean's class * @param c * @return */public static Map Getbeansbyclass (class C) {return Applicationcontext.getbeansoftype (c);}}
Non-web projects
ApplicationContext ac = new Filesystemxmlapplicationcontext ("Applicationcontext.xml")
The optional operating methods are:
A: string[] path={"Webroot/web-inf/applicationcontext.xml", "Webroot/web-inf/applicationcontext_task.xml"}; ApplicationContext context = new Filesystemxmlapplicationcontext (path); two: String path= "webroot/web-inf/ Applicationcontext*.xml "; ApplicationContext context = new Filesystemxmlapplicationcontext (path); III: ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Classpath: Address"); no classpath words are from the current working directory
Get spring's ApplicationContext and Bean objects manually