Spring--------Save Spring container in web App

Source: Internet
Author: User

---restore content starts---

Problem: I use the spring framework in a Web application, but some modules or components are not hosted for spring, such as some may be a WebService service class, what if I want to use managed objects in these unmanaged classes? Naturally, we need to get a reference to the Spring container object ApplicationContext, and my idea is that after the service is started, I'll try to save the application of the ApplicationContext container to a static variable, which is easy to use later.

1) just started with the spring+struts2, the strength of the words spring with Contextloaderlistener, as follows

<Context-param><Param-name>Contextconfiglocation</Param-name><Param-value>/web-inf/conf/comm/applicationcontext-*.xml</Param-value></Context-param><Listener><Listener-class>Org.springframework.web.context.ContextLoaderListener</Listener-class></Listener>

In this case, by writing a listener, the Web. XML is configured after the instantiation of Spring , and the spring container is saved in the Contextinitialized method.

 public  class  Applicationcontextlistener implements   servletcontextlistener{ public  void   Contextdestroyed (servletcontextevent arg0) {}  public  void   contextinitialized ( Servletcontextevent event) {C.WAC  = Webapplicationcontextutils.getwebapplicat        Ioncontext (Event.getservletcontext ());            System.out.println ( "Store Spring container end: applicationcontext=" +C.WAC); }    }

2) Write a new project today and try spring MVC and learn to do it, and the first thing is naturally to map some of the things in spring+struts2 to spring MVC. Naturally saving a reference to a spring container becomes one of the mappings, because spring MVC is initialized with a servlet (Dispatcherservlet), so it is impossible to save the container with listener (instantiation order ). Listener, filter, and servlet ), just started with Servlets, by configuring <load-on-startup> Controls the instantiation of the servlet after the spring servlet, but somehow it is impossible to get the spring container and always report a null pointer exception. Finally, there is no way to give up. Can only change the idea, found on the Internet a Applicationcontextaware interface, When the managed object that implements the interface is instantiated, spring passes the ApplicationContext object through the Setapplicationcontext method, which is the same design as Sessionaware in Struts2, and so on. The test can get a reference to the Spring container object, as follows (here's a little bit of knowledge, spring is instantiated directly at startup for Singleton objects, so you don't have to set scope when you configure the object, you can use the default)

@Component  Public class Implements   applicationcontextaware{    @Override    public void  Setapplicationcontext (applicationcontext ac)            throws  beansexception {        / / Store Spring container reference        C.WAC = ac;    }}

3) By implementing Applicationcontextaware has been able to obtain a container reference, but there is a problem, if you want to do something in the spring container instantiation, such as starting a maintenance thread to do some maintenance work, the work may be used in the spring container. The above method does not guarantee that the spring container is initialized when you get the Spring container reference. Further search finds spring provides some event monitoring

Spring provides built-in classes of events: Contextclosedevent, Contextrefreshedevent (Spring instantiation is complete), contextstartedevent (before spring instantiation), Contextstoppedevent (after spring destruction), requesthandleevent

One of the contextrefreshedevent formally we need, after the spring container boot completes will trigger the Contextrefreshedevent event, the monitoring method is as follows, implements

Applicationlistener, generic parameter contextrefreshedevent, similar to other event monitoring
@Component Public classInitlistenerImplementsApplicationlistener<contextrefreshedevent>{@Override Public voidonapplicationevent (contextrefreshedevent e) {webapplicationcontext WAC=(Webapplicationcontext) e.getapplicationcontext (); //storing spring container referencesC.WAC =WAC;  System.out.println (C.WAC); //Store configuration file pathC.conf_path = Wac.getservletcontext (). Getrealpath ("/web-inf/conf");  System.out.println (C.conf_path); //Initialize log4jPropertyconfigurator.configure (c.conf_path+ "/comm/log4j.properties"); //start the system cacheC.wac.getbean (CacheManager.class). Start ();}}

---restore content ends---

Spring--------Save Spring container in web App

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.