Three ways to get spring's applicationcontext in web development

Source: Internet
Author: User

In web development, there may be little need to show applicationcontext to get some beans managed by Spring, and today I've come across, and here's to share with you, how to get applicationcontext in web development

To get ApplicationContext, you must first understand how Spring's internal applicationcontext is stored. Let's follow the source code.

First: Start with the places you know best

Java code
    1. <listener>
    2. <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
    3. </listener>

The above paragraph, we are very familiar with it. Well, let's take a look at what it really does.

Java code
  1. Public class Contextloaderlistener<span style="color: #ff0000;" > <span style="color: #000000;" >implements servletcontextlistener</span></span> {
  2. private Contextloader Contextloader;
  3. /** 
  4. * Initialize the root Web application context.
  5. */
  6. public void <span style="color: #000000;" >contextInitialized</span> (Servletcontextevent event) {
  7. This.contextloader = Createcontextloader ();
  8. this.contextloader.<span style="color: #000000;"  >initWebApplicationContext</span> (Event.getservletcontext ());
  9. }//below is slightly


Obviously, Contextloaderlistener implements the Serveletcontextlistenet, and when the ServletContext is initialized, it will initialize the spring, and you will certainly think, Spring initialization should have something to do with ServletContext, right? Does it matter? Then let's get into

Contextloader.initwebapplicationcontext method

Java code
    1. Public Webapplicationcontext Initwebapplicationcontext (ServletContext servletcontext)
    2. throws IllegalStateException, beansexception {
    3. //Find from ServletContext, whether there is a <span style= "color: #000000;" Value of >webapplicationcontext.root_web_application_context_attribute as key </span>
Java code
  1. if (<span style="color: #ff0000;" ><span style="color: #000000;" >servletcontext.getattribute (webapplicationcontext.root_web_application_context_attribute)! = null</ Span><span style="color: #000000;" >) </span></span> {
  2. throw New IllegalStateException (
  3. "Cannot initialize context because there is already a root application context present-" +
  4. "Check whether you had multiple contextloader* definitions in your web.xml!");
  5. }
  6. try {
  7. //Determine parent for root Web application context, if any.
  8. ApplicationContext parent = Loadparentcontext (ServletContext);
  9. //It is available on ServletContext shutdown.
  10. This.context = Createwebapplicationcontext (ServletContext, parent);
  11. //Put ApplicationContext into ServletContext with key <span style= "color: #000000;" >WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE</span>
Java code
    1. <span style="color: #000000;" > <span>servletcontext.setattribute (webapplicationcontext.root_web_application_context_attribute, t His.context);</span></span>
    2. //Put ApplicationContext into the global static constant map of Contextloader, where key is: <span style= "color: #000000;" >thread.currentthread (). Getcontextclassloader () is the current thread class loader </span>
Java code
    1. Currentcontextperthread.put (Thread.CurrentThread (). Getcontextclassloader (), this.context);
    2. return This.context;
    3. }

From the code above, you should understand that after spring initialization, ApplicationContext is stored in two places, does that mean we can get applicationcontext in two ways?

The first method of obtaining:


Note: Webapplicationcontext.root_web_application_context_attribute = WebApplicationContext.class.getName () + ". ROOT ";

That is "Org.springframework.web.context.WebApplicationContext.ROOT"

So can we get applicationcontext this way:

Java code
    1. Request.getsession (). Getservletcontext (). getattribute (" Org.springframework.web.context.WebApplicationContext.ROOT ")

Yes, and when we think of this approach, spring has already provided us with an interface:

Java code
  1. Public Abstract class Webapplicationcontextutils {
  2. Public static Webapplicationcontext Getrequiredwebapplicationcontext (ServletContext SC)
  3. throws IllegalStateException {
  4. <span style="color: #000000;" >webapplicationcontext WAC = Getwebapplicationcontext (SC);</span>
  5. if (WAC = = null) {
  6. throw New IllegalStateException ("No webapplicationcontext found:no contextloaderlistener registered?");
  7. }
  8. return WAC;
  9. }

The Getwebapplicationcontext method is as follows:

Java code
    1. Public static Webapplicationcontext Getwebapplicationcontext (ServletContext SC) {
    2. return Getwebapplicationcontext (SC, webapplicationcontext.root_web_application_context_attribute);
    3. }

Haha, you see, it's the same way we do it ourselves.

Now look at the second method:

When it comes to spring initialization, the ApplicationContext is saved in a map to Contextloader, so can we pass map.get (key)??? Unfortunately, this map is private. Look:

Java code
    1. <span style="color: #000000;" >private</span> static final Map Currentcontextperthread =  Collectionfactory.createconcurrentmapifpossible (1);

Don't worry, however, that spring offers us a way: Look again:

Java code
    1. <span style="color: #000000;" >public static</span> webapplicationcontext Getcurrentwebapplicationcontext () {
    2. return (Webapplicationcontext) Currentcontextperthread.get (Thread.CurrentThread (). Getcontextclassloader ());
    3. }

We are relieved of this! Haha, the second method is also taken care of. What good is the second approach compared to the first? Is that it does not require parameters, as long as in the Web container, when spring initialization, you do not need to pass any parameters, you can get ApplicationContext to serve us. Isn't it good? However, when using this method, the author found that it does not exist in the Spring2.52 version, but it is available in version 2.5.5!!

In fact, the second method looks simple, but his principle is still a certain difficulty, he and the class loader thread context-related, have not know everyone has heard, this thread context in our common MySQL driver useful to, next time you can share with everyone.

The third way: Borrowing Applicationcontextaware,applicationcontext's help class can自动装载ApplicationContext,只要你将某个类实现这个接口,并将这个实现类在Spring配置文件中进行配置,Spring会自动帮你进行注

入 ApplicationContext.ApplicationContextAware的代码结构如下:

Java code
    1. Public interface Applicationcontextaware {
    2. void Setapplicationcontext (ApplicationContext applicationcontext) throws beansexception;
    3. }

On this one interface. A Applicationcontexthelper class can be implemented as simple as this:

Java code
  1. Public class Applicationhelper implements Applicationcontextaware {
  2. <span style="color: #000000;" >Private applicationcontext applicationcontext;</span>
  3. public void Setapplicationcontext (ApplicationContext applicationcontext)
  4. throws Beansexception {
  5. this.applicationcontext = ApplicationContext;
  6. }
  7. Public applicationcontext<span style="color: #000000;" > <span>getapplicationcontext () {</span></span>
  8. return This.applicationcontext;
  9. }
  10. }

By Applicationhelper, we can get the Appilcationcontext class we want.

Three ways to get spring's applicationcontext in web development

Related Article

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.