Sping Learning notes 9--spring ApplicationContext

Source: Internet
Author: User
I. Initialization of Applicationcontextaware

The spring container invokes the Applicationcontextaware Setapplicationcontext method. In the Applicationcontextaware implementation class, you can get the bean for the spring container from this object. 1. Implement Applicationcontextaware Interface:

Package com.bis.majian.practice.module.spring.util; 
Import org.springframework.beans.BeansException; 
Import Org.springframework.context.ApplicationContext; 
Import Org.springframework.context.ApplicationContextAware; 
public class Springcontexthelper implements Applicationcontextaware { 
    private static applicationcontext context = null; 

    @Override public 
    void Setapplicationcontext (ApplicationContext applicationcontext) 
            throws Beansexception { Context 
        = ApplicationContext; 
    } 
    public static Object Getbean (String name) {return 
        Context.getbean (name); 
    } 

2. Configure this class in spring's configuration file
<?xml version= "1.0" encoding= "UTF-8"?> "<beans xmlns=" http:// Www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:tx=" http:// Www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "Xsi:schemalocat ion= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring- Tx-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring- Context-3.0.xsd "default-autowire=" byname "> <bean id=" springcontexthelper "class=" Com.bis.majian.practice.mo Dule.spring.util.SpringContextHelper "></bean> <context:component-scan base-package=" Com.bis.majian.practice.module.* "/> </beans> 

The spring container calls Setapplicationcontext 3 after loading the spring container . The Web.xml configuration in the Web project loads the listener of the spring container

<!--initialize the spring container and let the spring container start automatically with Web application startup--> 
<listener> 
    <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class> 
4. Call

In your project, you can invoke the Getbean () method to get the objects in the spring container through this springcontexthelper. Second, applicationcontext loading mechanism 1. The loader currently has two options: Contextloaderlistener and Contextloaderservlet.

The two are functionally equivalent, but one is based on the new listener interface implementation in the Servlet2.3 version and the other based on the Servlet interface implementation. Development can be based on the actual situation of the target Web container selection. The configuration is very simple and increases in Web.xml:

<listener>   
    <listener-class>   
              Org.springframework.web.context.ContextLoaderListener   
    < /listener-class>   

Or

<servlet>  
    <servlet-name>context</servlet-name>  
    <servlet-class>  
       Org.springframework.web.context.ContextLoaderServlet  
    </servlet-class>  
    <load-on-startup>1 </load-on-startup>  
</servlet>

With the above configuration, the WEB container automatically loads the/web-inf/applicationcontext.xml initialization ApplicationContext instance, and if you need to specify a configuration file location, you can specify it by Context-param:

<context-param>
  <param-name>contextConfigLocation</param-name>  
  <param-value> Classpath:applicationcontext-bean.xml,classpath:spring-jamon.xml </param-value>
</context-param >
2. Spring provides applicationcontext multiple implementation mechanisms

Simple to test with ApplicationContext, get the Bean instance (object) defined in spring. You can use:

ApplicationContext ac = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Registerdao Registerdao = (Registerdao) ac.getbean ("Registerdao");

If it is more than two:
applicationcontext ac = new Classpathxmlapplicationcontext (new string[]{"Applicationcontext.xml", " Dao.xml "});

Or use wildcard characters:
applicationcontext ac = new Classpathxmlapplicationcontext ("Classpath:/*.xml");

The 3 implementations that spring provides for ApplicationContext are:

Classpathxmlapplicationcontext,filesystemxmlapplicationcontext and Xmlwebapplicationcontext, Where Xmlwebapplicationcontext is specifically designed for Web engineering.

Where Xmlwebapplicationcontext is specifically designed for Web engineering. Examples of use are as follows: I. Filesystemxmlapplicationcontext

Load a single configuration file
applicationcontext ctx = new Filesystemxmlapplicationcontext ("Bean.xml");       
String[] Locations = {"Bean1.xml", "Bean2.xml", "Bean3.xml"};     Load multiple configuration files
applicationcontext ctx = new Filesystemxmlapplicationcontext (locations);  Loading files according to specific path
ApplicationContext ctx =new filesystemxmlapplicationcontext ("D:/project/bean.xml");

Note: This approach applies to stand-alone applications that adopt the spring framework, requiring that the program manually initialize spring with a configuration file. Ii. Classpathxmlapplicationcontext

Load a single configuration file
applicationcontext ctx = new Classpathxmlapplicationcontext ("Bean.xml");
After the configuration is complete, the Webapplicationcontext Webapplicationcontext can be obtained through the Contextloader tool class
WAC = Contextloader.getcurrentwebapplicationcontext ();
Iii. Xmlwebapplicationcontext
ServletContext ServletContext = Request.getsession (). Getservletcontext ();    
ApplicationContext CTX = Webapplicationcontextutils.getwebapplicationcontext (ServletContext);

This approach is suitable for the B/s system using the spring framework, obtaining the ApplicationContext object through the ServletContext object, and then obtaining the required class instances through it. 3. How to Obtain ApplicationContext I. Inherit from abstract class Applicationobjectsupport

Description: Abstract class Applicationobjectsupport provides Getapplicationcontext () method, which can be easily obtained to ApplicationContext.
When spring initializes, the ApplicationContext object is injected through the Setapplicationcontext (ApplicationContext context) method of the abstract class. Ii. inheriting from abstract class Webapplicationobjectsupport

Description: Similar to the above method, call Getwebapplicationcontext () to obtain Webapplicationcontext Iii. implementation 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 by this method.
Implementation method:

public void Setapplicationcontext (ApplicationContext arg0) throws Beansexception {   
    applicationcontext = arg0; 
}
//Get the Bean:
Itaskservice bean = (itaskservice) Applicationcontext.getbean (taskservicename);
Spring get webapplicationcontext as null solution

To configure spring in Web.xml, configure the following

<servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class>
    <init-param>         
    < Param-name>contextconfiglocation</param-name>        
    <param-value>/web-inf/applicationcontext.xml </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</ Servlet>

Through Webapplicationcontextutils.getwebapplicationcontext (Getservletcontext ()) in the servlet Gets the Webapplicationcontext object as null. This is because, in addition to configuring Dispatcherservlet, you need to configure Contextloaderservlet, otherwise you cannot get webapplicationcontext. The configuration method is as follows, adding in the Web.xml

<servlet>
        <servlet-name>context</servlet-name>
        <servlet-class> Org.springframework.web.context.contextloaderservlet</servlet-class>
        <load-on-startup>2</ Load-on-startup>
 </servlet>

Lookup Reason: XML file loading sequence is incorrect, Servicebeanutils has not yet been loaded, ApplicationContext has not been initialized, and when the service starts a class is initialized by invoking ApplicationContext to fetch the bean.

Solution: Load the Servicebeanutils class first, initialize the ApplicationContext, and then load the class to invoke ApplicationContext to initialize the class Iv. ApplicationContext initialization mode 1. In a standalone application, get the ApplicationContext:

    Abstractapplicationcontext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
    Context.close ()//Releasing Resources
2. In the Web environment, get ApplicationContext: i.
ServletContext ServletContext = Request.getsession (). Getservletcontext ();               

II.
String ContextPath = "Org.springframework.web.context.WebApplicationContext.ROOT";

Webapplicationcontext context = Request.getsession (). Getservletcontext (). getattribute (ContextPath);   
Summary of common ways to get beans in spring method One: Save the ApplicationContext object when initializing
ApplicationContext ac = new Filesystemxmlapplicationcontext ("Applicationcontext.xml");
Ac.getbean ("Beanid");

Note: This approach applies to stand-alone applications that use the spring framework, and requires programs to manually initialize the spring by using a configuration file. method Two: Get the ApplicationContext object from the tool class provided by spring

Import Org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext AC1 = webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC);
ApplicationContext AC2 = webapplicationcontextutils.getwebapplicationcontext (ServletContext SC);
Ac1.getbean ("Beanid");
Ac2.getbean ("Beanid");

This approach is suitable for the B/s system using the spring framework, obtaining the ApplicationContext object through the ServletContext object, and then obtaining the required class instances through it. method Three: 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 by this method.

Be sure to use the common Java classes that implement these classes or interfaces must be configured in the spring configuration file Application-context.xml file. Otherwise, the obtained ApplicationContext object will be null.

Turn from:
Http://www.cnblogs.com/kxdblog/p/5988027.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.