Problem title, this article presents a solution that meets the following requirements:
(1) When the Web starts, the context of spring is automatically acquired so that the user can freely get the beans.
(2) in a single-file test environment, the spring context can also be loaded according to the profile path.
The approximate principle is:
When Spring starts, it gives any bean that implements the Applicationcontextaware interface (which can also be called a Class), injecting a constructor parameter: ApplicationContext.
With such a class, you can easily get the context in your own code.
The advantage of writing such a class is that, when a class is called, it is not launched through the web (then it is not injected) and can be judged by the context object being empty.
The source code for such a class is:
Import Org.apache.tiles.velocity.template.getasstringdirective;import org.springframework.beans.BeansException; Import Org.springframework.context.applicationcontext;import Org.springframework.context.ApplicationContextAware ; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.context.support.filesystemxmlapplicationcontext;public class Mybeanfactory Implements Applicationcontextaware{public static ApplicationContext context = null; @Overridepublic void Setapplicationcontext ( ApplicationContext ApplicationContext) throws Beansexception{if (Context==null) {context =applicationcontext;} System.out.println ("ApplicationContext setter is called ..."); public static ApplicationContext Getapplicationcontext () {if (context==null) {//local debug context = new Filesystemxmlapplicationcontext ("/webcontent/web-inf/config/spring-context.xml");} return context;} public static Object Getbean (String name) {if (context==null) {context = Getapplicationcontext ();} Return CONtext.getbean (name);}}
How to get the spring context when the web starts