How to obtain Spring ApplicationContext

Source: Internet
Author: User

In WEB development, you may rarely need to display the ApplicationContext to get some beans managed by Spring. Today I have met them. Here I will share with you about WEB development, how to obtain ApplicationContext

First, you must understand how ApplicationContext is stored in Spring. Next let's track the source code

First, start from what you are most familiar.

Java code
  1. Org. springframework. web. context. ContextLoaderListener
  2. You are familiar with the above section. Well, let's see what it actually achieves.

    Java code
    1. Public class ContextLoaderListener implements ServletContextListener {
    2. Private ContextLoader contextLoader;
    3. /**
    4. * Initialize the root web application context.
    5. */
    6. Public void contextInitialized (ServletContextEvent event ){
    7. This. contextLoader = createContextLoader ();
    8. This. contextLoader. initWebApplicationContext (event. getServletContext ());
    9. } // The following


      Apparently, ContextLoaderListener implements ServeletContextListenet. Spring initialization will be performed during ServletContext initialization. You will surely think that Spring initialization should be related to ServletContext? Does it matter? Next let's go

      ContextLoader. initWebApplicationContext Method

      Java code
      1. Public WebApplicationContext initWebApplicationContext (ServletContext servletContext)
      2. Throws IllegalStateException, BeansException {
      3. // Check from ServletContext whether Java code with the value of WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE as the Key exists.
        1. If (servletContext. getAttribute (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE )! = Null ){
        2. Throw new IllegalStateException (
        3. "Cannot initialize context because there is already a root application context present-" +
        4. "Check whether you have 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, whose key is WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE Java code
          1. ServletContext. setAttribute (WebApplicationContext. ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this. context );
          2. // Put ApplicationContext into the Global static constant Map of ContextLoader. The key is Thread. currentThread (). getContextClassLoader (), that is, the Java code of the current Thread-class loader.
            1. CurrentContextPerThread. put (Thread. currentThread (). getContextClassLoader (), this. context );
            2. Return this. context;
            3. }

              From the above Code, we should understand that after Spring initialization, ApplicationContext is stored in two places. Does it mean that we can get ApplicationContext in two ways?

              Method 1:


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

              It is org. springframework. web. context. WebApplicationContext. ROOT"

              Can we obtain ApplicationContext like this:

              Java code
              1. Request. getSession (). getServletContext (). getAttribute ("org. springframework. web. context. WebApplicationContext. ROOT ")

                Indeed, we can. When we think of this method, Spring has provided us with Interfaces:

                Java code
                1. Public abstract class WebApplicationContextUtils {
                2. Public static WebApplicationContext getRequiredWebApplicationContext (ServletContext SC)
                3. Throws IllegalStateException {
                4. WebApplicationContext wac = getWebApplicationContext (SC );
                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, see it. It is the same as what we implement.

                    This method is generally used when you define a Listener and implement the ServletContextListener interface. In web. xml, You need to configure this Listener.

                                       
                                         
                                        
                                         
                    Cn. itcast. oa. Utils. InitListener
                                        
                                       
                    The listener class is as follows:

                    Public class InitListener implements ServletContextListener {// initialize public void contextInitialized (ServletContextEvent sce) for the maximum value {// obtain the container and related Service object ApplicationContext ac = WebApplicationContextUtils. getWebApplicationContext (sce. getServletContext (); PrivilegeService privilegeService = (PrivilegeService) ac. getBean ("privilegeServiceImpl"); // prepare data: topPrivilegeListList
                                       
                                        
                    TopPrivilegeList = privilegeService. findTopList (); sce. getServletContext (). setAttribute ("topPrivilegeList", topPrivilegeList); System. out. println ("------------> prepared data <------------");} public void contextDestroyed (ServletContextEvent arg0 ){}}
                                       


                    There is also a simple

                    Code:
                    ApplicationContext ac = new FileSystemXmlApplicationContext ("applicationContext. xml ");
                    Ac. getBean ("beanId ");
                    Note: This method is applicable to standalone applications using the Spring framework. You need to manually initialize Spring through the configuration file.

                    Then ..... After obtaining the ApplicationContext object, you can get getBean ..... La la

                    Reference http://www.blogjava.net/Todd/archive/2010/04/22/295112.html


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.