Get ApplicationContext (@AutoWired, Applicationlistener) in spring code

Source: Internet
Author: User

2017 annual net Original it Bo main selection campaign vote: http://www.itbang.me/goVote/234

Learning Spring frame time is not long, every bit has to be pro-force. Today, I suddenly feel that the automatic loading of components through the @autowired is not very comfortable, always want to write annotations under the class. So consider getting applicationcontext directly, calling Getbean to get the bean instance you want. On-line data, the beginning of the wrong direction, through the way of loading XML initialization ApplicationContext, it is a ridiculous process, we are obviously blind to engage in. The following is about what I learned now, two kinds: 1, with @autowired directly assembled applicationcontext;2, with Applicationlistener monitoring contextrefreshedevent events, when the context is refreshed, Save the ApplicationContext to the global object.

First, with @autowired directly assembled ApplicationContext. Simple, simple to put down the code.

     @Autowired    applicationcontext context;         = "/login2")    public  String login2 (string name, model model, HttpServletRequest request, HttpSession session) {                context.getbean (requestbean.  Class). Printid ();

Second, monitor contextrefreshedevent events with Applicationlistener. Individuals prefer this implementation by not having to write @autowired annotations, and then continue to use spring to automate the management of components.

Simple description: Applicationlistener is an application event watcher, can listen to applicationevent of various extension classes, this is very interesting, we can define their own events, Then use Applicationlistener to monitor. Attach a bit of source code below

  

1. Define a context management tool (global use)

 Packagesimm.spring.common.utils;ImportOrg.springframework.context.ApplicationContext;/*** Context Acquisition Tool class *@authorWh-simm **/ Public classApplicationcontextutil { Public StaticApplicationcontextutil instance =NewApplicationcontextutil (); PrivateApplicationContext _context; PrivateApplicationcontextutil () {} Public voidinit (ApplicationContext context) {_context=context; }     PublicApplicationContext GetContext () {return_context; }    /*** Get Bean *@paramRequiredtype *@return     */     Public<T> T Getbean (class<t>requiredtype) {        return_context.getbean (requiredtype); }}

2, the implementation of the context of the completion of the initialization or refresh of the listening method, ApplicationContext to obtain and save

 Packagesimm.spring.web.events;ImportOrg.springframework.context.ApplicationListener;Importorg.springframework.context.event.ContextRefreshedEvent;ImportOrg.springframework.stereotype.Service;Importsimm.spring.common.utils.ApplicationContextUtil; @Service Public classContextrefreshlistenerImplementsApplicationlistener<contextrefreshedevent>{@Override Public voidonapplicationevent (Contextrefreshedevent event) {//TODO auto-generated Method Stub        if(Event.getapplicationcontext (). GetDisplayName (). Equals ("Root webapplicationcontext") {System.out.println ("Avoid spring-servlet.xml and appicationcontext.xml two times"); }        if(Event.getapplicationcontext (). getParent () = =NULL) {System.out.println ("Perform context contexts initialization");        ApplicationContextUtil.instance.init (Event.getapplicationcontext ()); }    }}

3. Next, show the new calling method. Now this call will no longer have to consider whether the successful completion of the @autowired, in the business code can be used freely. There is wood to feel a hint of refreshing!

ApplicationContextUtil.instance.getBean (Requestbean.  Class). Printid ();

This is a bit of my experience with ApplicationContext. Not many things, I hope you have some help, welcome message exchange.

Get ApplicationContext (@AutoWired, Applicationlistener) in spring code

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.