The role of the Applicationcontextaware interface

Source: Internet
Author: User

1/==============

in a Web application, Spring containers are typically generated in a declarative manner: as long as the developer configures a listener in Web. XML, the listener will be responsible for initializing the spring container, and the MVC framework can directly invoke the beans in the spring container without having to access the spring container itself. In this case, the bean in the container is under container management without having to actively access the container, just accept the container's dependency injection. However, in some special cases, the bean needs to implement a function, but the function must be implemented with the help of the spring container, so that the bean must get the spring container first and then implement it with the help of the spring container. In order for the bean to get the spring container it is in, you can have the bean implement the Applicationcontextaware interface. The following example is a tool class that implements Applicationcontextaware, which can be referenced by other classes to manipulate the spring container and the bean instances in it.  Public classSpringcontextholderImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext =NULL; /*** Gets the ApplicationContext in the static variable. */     Public StaticApplicationContext Getapplicationcontext () {assertcontextinjected (); returnApplicationContext; }     /*** Get the bean from the static variable ApplicationContext and automatically transform it to the type of the assigned value object. */@SuppressWarnings ("Unchecked")     Public Static<T>T Getbean (String name) {assertcontextinjected (); return(T) Applicationcontext.getbean (name); }     /*** Get the bean from the static variable ApplicationContext and automatically transform it to the type of the assigned value object. */     Public Static<T> T Getbean (class<t>requiredtype)        {assertcontextinjected (); returnApplicationcontext.getbean (requiredtype); }     /*** Clear ApplicationContext in Springcontextholder is null. */     Public Static voidClearholder () {ApplicationContext=NULL; }     /*** Implement the Applicationcontextaware interface and inject the context into the static variable. */@Override Public voidSetapplicationcontext (ApplicationContext applicationcontext) {Springcontextholder.applicationcontext=ApplicationContext; }     /*** Check that the ApplicationContext is not empty. */    Private Static voidassertcontextinjected () {validate.validstate (ApplicationContext!=NULL,                "The Applicaitoncontext property is not injected, define Springcontextholder in Applicationcontext.xml."); }} The Spring container detects all the beans in the container, and if a bean is found to implement the Applicationcontextaware interface, the spring container will, after the bean is created, The Bean's Setapplicationcontextaware () method is called automatically, and when the method is called, the container itself is passed as an argument to the method- The implementation part of the method assigns spring-passed parameters (the container itself) to the ApplicationContext instance variable of the class object, so the container itself can then be accessed through the ApplicationContext instance variable. Example: Creating an CacheManager instance in Cacheutil with the spring container Public classCacheutils {Private StaticCacheManager CacheManager = ((CacheManager) Springcontextholder.getbean ("CacheManager")); }

2/==========================

What is the use of this interface? Once a class implements this interface (Applicationcontextaware), this class can easily get all the beans in the ApplicationContext. In other words, this class can get directly from the spring configuration file, all the bean objects that are referenced to. Second, how to use? For example, I have a method class Apputil, a bean (companyservice) in the applicationcontext that needs to be used in this method class. 1, because spring wants to build its own container, it has to load its own configuration file. At this point, you need to register Contextloaderlistener or subclasses of this class. Add the following information to Web. xml:<listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener>Of course, this will only read the Application.xml configuration file under the default path. If you need to read the configuration file under a specific path. You need to add the following information in Web. Xml. You can refer to my example and specify the configuration file as follows:<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpat H:conf/app-context.xml</param-value> </context-param>Note:<param-name>contextConfigLocation</param-name>is not to be changed. 2, Method Class Apputil processing method class Apputil implement Applicationcontextaware interface: Public classApputilImplementsApplicationcontextaware An object that adds a static member ApplicationContext type to the method class Apputil. After the method class Apputil gets ApplicationContext, it is by reading this member variable. The following are the specific examples:Private Staticapplicationcontext AppContext; The default method for implementing the Applicationcontextaware interface: Public voidSetapplicationcontext (ApplicationContext paramapplicationcontext)throwsbeansexception {appContext=Paramapplicationcontext; } 3, in the spring configuration file, the registration method class Apputil Strictly speaking, the method class Apputil is a bean, and from step 2 we are not difficult to find, The method class Apputil has the flexibility to get applicationcontext because spring can automate setapplicationcontext for us. However, Spring does not perform its methods for a class for no reason, so it is necessary to inform spring of the existence of such a subclass by registering the method class Apputil. (When the spring configuration file is loaded, if the bean class defined in the spring configuration file implements the Applicationcontextaware interface, when the spring configuration file is loaded, is automatically called in the Applicationcontextaware interface. Public voidSetapplicationcontext (ApplicationContext context)throwsThe Beansexception method obtains the ApplicationContext object, and the ApplicationContext object is injected by spring. This class must be specified in the spring configuration file) In fact, the method is simply to register the method class Apputil as a normal bean in the spring configuration file:<bean id= "Apputil"class= "Com.htsoft.core.util.AppUtil"/>4, using static members of the ApplicationContext type Object, AppContext, to invoke other beans. Add the following method to the method class Apputil: Public StaticObject Getbean (String paramstring) {returnAppcontext.getbean (paramstring); Then, in the method class Apputil, you have the flexibility to invoke any other bean, for example: Companyservice localcompanyservice= (Companyservice) getbean ("Companyservice"Note: The contents of the configuration file about Companyservice:<bean id= "Companyservice"class= "Com.kaiwii.service.system.impl.CompanyServiceImpl" > <constructor-arg index= "0" ref= "Companydao"/> & Lt;/bean>

The role of the Applicationcontextaware interface

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.