001-spring several ways to get beans in code

Source: Internet
Author: User

I. Overview

Method One: Save the ApplicationContext object at initialization time

Method Two: Get the ApplicationContext object through the Utils class provided by spring

Method Three: Inherit from abstract class Applicationobjectsupport

Method Four: Inherit from abstract class Webapplicationobjectsupport

Method Five: Implement Interface Applicationcontextaware

Method Six: Through spring-provided Contextloader

Second, Detailed introduction

1. Save the ApplicationContext object "standalone application with Spring framework" at initialization

New Filesystemxmlapplicationcontext ("Applicationcontext.xml");   Ac.getbean ("Beanid");  

Description: This approach applies to standalone applications that use the spring framework, requiring the program to manually initialize the spring with a configuration file.

Method Two: Obtain the ApplicationContext object "b/S System" through the tool class provided by spring
ApplicationContext AC1 = webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC);    = Webapplicationcontextutils.getwebapplicationcontext (ServletContext SC);   Ac1.getbean ("Beanid");   Ac2.getbean ("Beanid");  

Description: This method is suitable for using the spring framework of the B/s system, through the ServletContext object to obtain the ApplicationContext object, and then through it to obtain the required class instance. The difference between the above two tool methods is that the former throws an exception when it gets failed, and the latter returns null.

Method Three: Inherit from abstract class Applicationobjectsupport

Description: Abstract class Applicationobjectsupport provides the Getapplicationcontext () method, which makes it easy to get applicationcontext.

When spring initializes, the ApplicationContext object is injected through the Setapplicationcontext (ApplicationContext context) method of the abstract class.

Method Four: Inherit from abstract class Webapplicationobjectsupport

Description: Similar to the above method, call Getwebapplicationcontext () to get Webapplicationcontext

Method Five: Implement Interface Applicationcontextaware

Description: Implements the Setapplicationcontext (ApplicationContext context) method of the interface and saves the ApplicationContext object. When spring initializes, the ApplicationContext object is injected through this method.

Here is the code to implement the Applicationcontextaware interface, which is similar to the previous two methods:

 Public classSpringcontextutilImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext; /*** Implement the context injection function of the Applicationcontextaware interface and store it in a static variable. */       Public voidSetapplicationcontext (ApplicationContext applicationcontext) {Springcontextutil.applicationcontext= ApplicationContext;//Nosonar    }        /*** Gets the applicationcontext stored in the static variable. */       Public StaticApplicationContext Getapplicationcontext () {checkapplicationcontext (); returnApplicationContext; }        /*** Gets the bean from static variable ApplicationContext, automatically transforms to the type of the assigned value object. */@SuppressWarnings ("Unchecked")       Public Static<T>T Getbean (String name) {Checkapplicationcontext (); return(T) Applicationcontext.getbean (name); }        /*** Gets the bean from static variable ApplicationContext, automatically transforms to the type of the assigned value object. */@SuppressWarnings ("Unchecked")       Public Static<T> T Getbean (class<t>clazz)          {Checkapplicationcontext (); return(T) Applicationcontext.getbeansoftype (clazz); }        /*** Clear ApplicationContext static variables. */       Public Static voidCleanapplicationcontext () {ApplicationContext=NULL; }        Private Static voidCheckapplicationcontext () {if(ApplicationContext = =NULL) {              Throw NewIllegalStateException ("Applicaitoncontext not injected, please define Springcontextholder in Applicationcontext.xml"); }      }    }  

Although spring provides the following three methods that can be implemented in ordinary classes to inherit or implement the corresponding class or interface to obtain the spring ApplicationContext object, but in use it is important to note that implementing these classes or interfaces of the ordinary Java class must be in the spring Configuration file in the Applicationcontext.xml file. Otherwise, the obtained ApplicationContext object will be null.

<bean id="Spring" class="springcontextutil"/>

Method Six: Through spring-provided Contextloader
Webapplicationcontext WAC = contextloader.getcurrentwebapplicationcontext ();  Wac.getbean (Beanid);  

Finally, a way to not rely on a servlet and not inject is provided. However, it is important to note that when the spring container is initialized, the spring container cannot be obtained by the following method when the server is started, and details can be viewed in spring source org.springframework.web.context.ContextLoader.

001-spring several ways to get beans in 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.