How to get the spring context when the web starts

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.