The scope and life cycle of spring bean

Source: Internet
Author: User

In the previous blog mentioned in the container launch Get Beandefinition object has a scope property. This property controls the scope of the Bean object. This section describes the scope and life cycle of the bean, and how it does not.

I. Scope of the Bean
The bean container starts reading the bean's XML configuration file, and then converts each bean element in the XML into a Beandefinition object. There is a scope property in the Beandefinition object, that is, it controls the scope of the bean.
The spring Framework supports 5 scopes, and three scopes are applied when developers use Web-based applicationcontext. Here is the scope of Spring direct support, and of course developers can customize the scopes themselves.

Scope

Describe

Single Case (singleton)

(default) Each Spring IoC Container has a unique instance object

Prototypes (prototype)

A Bean definition, any number of objects

request (request )

one http request produces a bean http request has its own bean example. web font-family spring applicationcontext available

session (session )

limit one bean web font-family spring applicationcontext to use

Global session

Limits the scope of a Bean to the life cycle of a global HTTPSession. Typically used for portal site scenarios, as well, only The Web- based Spring applicationcontext is available

We can demonstrate the singleton and prototype scopes based on the Xmlinstance class.
Here, the Bean object is obtained two times using the Getbean method of the beanfactory.

        Xmlinstance instance= (xmlinstance) Factory.getbean ("Xmlinstance");        Instance.setname ("123");        Instance. Breath ();        Instance= (xmlinstance) factory.getbean ("Xmlinstance");        Instance. Breath ();

If we adopt the bean default scope singleton, the following configuration, the objects obtained by the two Getbean are consistent.

  class= "Com.demo.model.XMLInstance" scope= "singleton" >      <property name= "Air" ref= "CleanAir" > </property>      <property name= "name" value= "abc" ></property>  </bean>
Output result: name:123; air:cleanairname:123; Air:cleanair

If we adopt the bean default scope singleton, the following configuration, the objects obtained by the two Getbean are inconsistent.

  class= "Com.demo.model.XMLInstance" scope= "prototype" >      <property name= "Air" ref= "CleanAir" > </property>      <property name= "name" value= "abc" ></property>  </bean>
Output result: name:123; AIR:CLEANAIRNAME:ABC; Air:cleanair

Second, the Bean's life cycle
The previous section describes the bean container and the bean's configuration and injection, and this chapter learns the Bean's life cycle to see how the bean is coming and how it is not.

In the ApplicationContext container, the life cycle flow of the bean as shown, the process is roughly as follows:
1. First the container is started, the scope is singleton and non-lazy loaded beans are instantiated,
2. According to the Bean definition information configuration information, inject all the attributes,
3. If the bean implements the Beannameaware interface, it will callback the interface's Setbeanname () method, passing in the Bean's ID, at which point the Bean obtains its own ID in the configuration file.
4. If the bean implements the Beanfactoryaware interface, it will callback the Setbeanfactory () method of the interface, passing in the Bean's beanfactory, so that the bean has its own beanfactory.
5. If the bean implements the Applicationcontextaware interface, it will callback the interface's Setapplicationcontext () method, passing in the applicationcontext of the Bean, So that the bean gets its own applicationcontext,
6. If a bean implements the Beanpostprocessor interface, it will callback the interface's Postprocessbeforeinitialzation () method,
7. If the bean implements the Initializingbean interface, it will callback the interface's Afterpropertiesset () method,
8. If the bean is configured with the Init-method method, the method of Init-method configuration is executed.
9. If a bean implements the Beanpostprocessor interface, it will callback the interface's Postprocessafterinitialization () method,
10. After the process 9, the bean can be formally used, for the bean,spring of the scope is singleton in the IOC container cache a copy of the Bean instance, and for the scope of prototype beans, Each time a new object is called, the lifecycle is left to the caller to manage, no longer the spring container.
11. When the container is closed, if the bean implements the Disposablebean interface, the Destroy () method of the interface is recalled,
12. If the bean is configured with the Destroy-method method, the method of Destroy-method configuration is executed, at which point the entire bean's life cycle ends. This is done on the basis of the Userbean class, which adds the name attribute and implements the Applicationcontextaware interface.
 PackageCom.demo.model;Importorg.springframework.beans.BeansException;Importorg.springframework.beans.factory.BeanFactory;ImportOrg.springframework.beans.factory.BeanFactoryAware;ImportOrg.springframework.beans.factory.BeanNameAware;ImportOrg.springframework.beans.factory.DisposableBean;ImportOrg.springframework.beans.factory.InitializingBean;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware; Public classUserBeanImplementsBeannameaware,beanfactoryaware,initializingbean,disposablebean,applicationcontextaware {PrivateString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; System.out.println ("The set method is called"); }     PublicUserBean () {System.out.println ("Userbean class Construction method"); }         Public voidsetbeanname (String name) {System.out.println ("Beannameaware is called"); }     Public voidSetbeanfactory (Beanfactory beanfactory)throwsbeansexception {System.out.println ("Beanfactoryaware is called"); }     Public voidAfterpropertiesset ()throwsException {System.out.println ("Initializingbean is called"); }     Public voidDestroy ()throwsException {System.out.println ("Disposablebean is called"); }    //Custom Initialization Functions     Public voidMyinit () {System.out.println ("Myinit is called"); }     //Custom Destruction Methods     Public voidMydestroy () {System.out.println ("Mydestroy is called"); }     Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {System.out.println ("Setapplicationcontext is called"); }}
View Code

The Post processor cusbeanpostprocessor is defined to implement the Beanpostprocessor interface.

 PackageCom.demo.model;Importorg.springframework.beans.BeansException;ImportOrg.springframework.beans.factory.config.BeanPostProcessor; Public classCusbeanpostprocessorImplementsBeanpostprocessor { PublicObject Postprocessbeforeinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Postprocessbeforeinitialization is called"); returnBean; }     PublicObject Postprocessafterinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Postprocessafterinitialization is called"); returnBean; }}

Configure the beans and beanpostprocessor in XML.

  <BeanID= "User"class= "Com.demo.model.UserBean"Destroy-method= "Mydestroy"Init-method= "Myinit">      < Propertyname= "Name"value= "ABC"></ Property>  </Bean>   <BeanID= "Postprocessor"class= "Com.demo.model.CusBeanPostProcessor" />

Test:

        ApplicationContext context=New classpathxmlapplicationcontext (new string[]{" Applicationcontext.xml "});        Beanfactory Factory=context;        UserBean User= (UserBean) context.getbean ("User");        ((classpathxmlapplicationcontext) context). Close ();

Output Result:
Userbean Class Construction method
The Set method is called
Beannameaware is called
Beanfactoryaware is called
Setapplicationcontext is called
Postprocessbeforeinitialization is called
Initializingbean is called
Myinit is called
Postprocessafterinitialization is called
Disposablebean is called
Mydestroy is called

The scope and life cycle of spring bean

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.