The life cycle of spring-managed beans

Source: Internet
Author: User

The timing of the Bean's initialization

The scope of the spring container-managed Bean is explained Earlier. Then we have to think about the question: when is the bean actually instantiated? We use this issue as a primer to start the description of this Article.
The Bean object is instantiated at the following two moments:

    1. When the Getbean () method is Called.
    2. When the Spring container starts.

so, at what point the Bean object is instantiated, there is a connection to the scope of the bean . We delve into the case of the scope of the bean that is configured for spring management . To be able to clearly see the instantiation of the bean object, we need to modify the code of the Personservicebean class To:

public class PersonServiceBean implements PersonService { public PersonServiceBean() { System.out.println("我被实例化了"); } @Override public void save() { System.out.println("我是save()方法"); }}
    • 1
  • When Spring's configuration file--beans.xml the contents of:

    <?xml version= "1.0" encoding= "UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http// Www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id=" Personservice "  class="cn.itcast.service.impl.PersonServiceBean" ></bean></beans> 
      • 1

    That is, when the scope of the bean is singleton, we modify the code of the Springtest class To:

    public class SpringTest {    @Test    public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 }}
      • 1

    At this point, the test () method, Eclipse console Output:

    I was Instantiated.

    This means that when the Bean's scope is singleton, The Bean object is created when the spring container is Started. That is, by default, The bean is initialized when the container starts, but we can also specify the bean Node's lazy-init= "true" to defer the initialization of the bean, when the bean is initialized only the first time it is Fetched. Such as:
    We will change the contents of the spring configuration File--beans.xml to:

    <?xml version= "1.0" encoding= "UTF-8"?>< beans xmlns= "/http" Www.springframework.org/schema/beans "xmlns:xsi="/http Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> Span class= "hljs-tag" ><bean id=  "personservice" class= " Cn.itcast.service.impl.PersonServiceBean "lazy-init=" True "></bean></ beans>             
      • 1

    At this point, the test () method is tested, and the Eclipse console does not output this sentence at all:

    I was Instantiated.

    lazy-init= "true" Specifies that the bean should not be instantiated when the spring container is Started.
    At this point, only the code for the Springtest class is modified To:

    public class SpringTest {    @Test    public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 PersonService personService = (PersonService) ctx.getBean("personService"); // 从Spring容器取得bean }}
      • 1

    Testing the test () method again, The Eclipse console will not output this sentence:

    I was Instantiated.

    If you want to apply lazy initialization to all beans, you can set default-lazy-init= "true" at the root node beans, as Follows:

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-lazy-init="true"> ......</beans>
      • 1
  • When Spring's configuration file--beans.xml the contents of:

    <?xml version= "1.0" encoding= "UTF-8"?><beans xmlns= "/http" Www.springframework.org/schema/beans "xmlns:xsi="/http Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> Span class= "hljs-tag" ><bean id=  "personservice" class= " Cn.itcast.service.impl.PersonServiceBean "scope=" Prototype "></bean></beans>            
      • 1

    That is, if the Bean's scope is prototype, the code for the Springtest class Is:

    public class SpringTest {    @Test    public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 }}
      • 1

    Testing the test () method, you can see that the Eclipse console did not output this sentence:

    I was Instantiated.

    This means that when the Bean's scope is prototype, The Bean object is not created when the spring container is Started.
    however, If you change the code of the Springtest class To:

    public class SpringTest {    @Test    public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 PersonService personService = (PersonService) ctx.getBean("personService"); // 从Spring容器取得bean }}
      • 1

    At this point, testing the test () method, you can see that the Eclipse console output this sentence:

    I was Instantiated.

    Confirms that when the Bean's scope is prototype, The Bean object is created when the Getbean () method is Called.

Specifying the initialization and destruction methods of the bean

We want to initialize some resources when the bean is Initialized. To achieve this, we can modify the code for the Personservicebean class:

public class PersonServiceBean implements PersonService { public void init() { System.out.println("初始化某些资源"); } public PersonServiceBean() { System.out.println("我被实例化了"); } @Override public void save() { System.out.println("我是save()方法"); }}
    • 1

In this way, our purpose becomes specific: when the spring container initializes the Personservicebean object, it executes the init () method of the Object. In order to achieve this, only the content of the spring configuration file--beans.xml should be modified:

<?xml version= "1.0" encoding= "UTF-8"?><Beansxmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation=<bean id=" personservice " class= "cn.itcast.service.impl.PersonServiceBean" lazy-init= "false" init-method=< Span class= "hljs-value" > "init"/></beans>   
    • 1
    • 2

If the code for the Springtest class Is:

public class SpringTest {    @Test    public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 }}
    • 1

Test () method, The Eclipse console will print:

Now we want to release or close some resources when the bean is Destroyed. To achieve this, we can modify the code of the Personservicebean class To:

PublicClassPersonservicebeanimplements personservice {public Span class= "hljs-keyword" >void init () {System.out.println ( " Initialization of certain resources "); } public personservicebean () {System.out.println (" I was instantiated "); }  @Override public void save () {System.out.println (/** * Bean exactly when was it destroyed? If it is not manually deleted, the bean is always in the spring container, which means that the bean will be destroyed as the spring container is Closed. */public void destroy () { System.out.println ( "releasing initialized resources")}}         
    • 1

Try to think about the question: when was the Bean object destroyed? The answer is: if it is not manually removed, the bean is always in the spring container, which means that the bean will be destroyed as the spring container is Closed.
Shortly thereafter, we want to modify the contents of Spring's configuration File--beans.xml.

<?xml version= "1.0" encoding= "UTF-8"?><Beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" Span class= "hljs-attribute" >xsi:schemalocation= http://www.springframework.org/schema/ Beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id=" personservice " class= "cn.itcast.service.impl.PersonServiceBean" lazy-init= "false" init-method=< Span class= "hljs-value" > "init" destroy-method= "destroy"/ ></beans>       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

finally, we want to modify the code for the test Class--springtest.java:

public class SpringTest {    @Test    public void test() { // ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器 AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); ctx.close(); // 正常关闭Spring容器 }}
    • 1

At this point, the test () method, the Eclipse console will print:

This is the life cycle of spring-managed Beans. Source code can be downloaded by clicking on the life cycle of the bean managed by spring .

The life cycle of spring-managed beans

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.