When I go to some enterprises for interviews, I am often asked about Spring. Once I was asked about the life cycle of beans in Spring. In fact, this is often encountered in business, but easy to forget, so special summary.

Tip: Learn from the Servlet lifecycle, instantiate, init, receive the requested Service, and destroy.

The full life cycle of the Bean

For normal Java objects, the object is created when new and collected by the garbage collection mechanism when it has no references. Objects hosted by the Spring IoC container, on the other hand, have their life cycles completely controlled by the container. The lifecycle of each Bean in Spring is as follows:

As shown in the figure above, the life cycle of a Bean is quite complex. Here is a text description of each step in the figure above:

Spring starts, finds and loads beans that need to be managed by Spring, and instantiates the beans

After the Bean is instantiated, the import and value of the Bean is injected into the Bean’s properties

Spring passes the Bean Id to the setBeanName() method if the Bean implements the BeanNameAware interface

If the Bean implements the BeanFactoryAware interface, Spring calls the setBeanFactory() method, passing in the BeanFactory container instance

If the Bean implements the ApplicationContextAware interface, Spring calls the Bean’s setApplicationContext() method, passing in a reference to the Bean’s application context

If the Bean implements the BeanPostProcessor interface, the Spring would call their postProcessBeforeInitialization () method.

If the Bean implements the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean declares an initialization method with init-method, that method will be called

If the Bean implements the BeanPostProcessor interface, the Spring would call their postProcessAfterInitialization () method.

At this point, the Bean is ready to be used by the application. They will reside in the application context until the application context is destroyed.

If the bean implements the DisposableBean interface, Spring will call its destory() interface method, which will also be called if the bean uses destory-method to declare the destruction method.

Watched so many interview questions to tell you the truth, the only answer to the interview content are most, in fact, a lot of the time we don’t really describe the interface to achieve the above said, if asked Spring Bean lifecycle, during an interview, I believe a lot of people say not to come out, the following I the three stages to a deep understanding of the life cycle of the beans, Let small partners more profound understanding!

Three phases of the life cycle

Start by adding spring’s scope

There are currently five main scopes or scopes for Spring beans.

singleton There is only one instance of a Bean in the Spring IoC container, and the Bean exists as a singleton, with the Bean scoped default value.
prototype Each time a Bean is called from the container, a new instance is returned, which is equivalent to executing newXxxBean() each time getBean() is called.
request Each HTTP request creates a new Bean, which is scoped only for the Web’s Spring WebApplicationContext.
session The same HTTP Session shares a Bean, and different sessions use different beans. This scope only applies to the Spring WebApplicationContext of the Web.
application Limits the scope of a Bean toServletContextLife cycle of. This scope only applies to the Spring WebApplicationContext of the Web.

First Creation phase

When the Spring factory creates objects

Scope = “singleton” (default)

Spring factory created at the same time, the object creation ClassPathXmlApplicationContext s1 = new ClassPathXmlApplicationContext (" application. XML "); <bean name="student" class="com.zq.student" scope="singleton" lazy-init="true"/> <bean name="student" class="com.zq.student" scope="singleton" lazy-init="true"/>Copy the code

The scope = “prototype”

The Spring factory creates objects as they are fetched. ClassPathXmlApplicationContext s1 =new ClassPathXmlApplicationContext("application.xml");
Object student = s1.getBean("student");
Copy the code

Second initialization phase

After the Spring factory creates the object, it calls the initialization method of the object to complete the corresponding initialization operation. 1. Initialization method provision: The programmer provides initialization methods based on requirements and finally completes initialization operations. 2. Initialize the method call: The Spring factory makes the callCopy the code

InitializingBean interface

@override public void afterPropertiesSet() throws Exception {// Write the initialization here. Database? System.out.println(" initialization method "); }Copy the code

Provide yourself with a normal method to configure to the configuration file

public void myInit(a){
    System.out.println("My own method of initialization.");
}
<bean name="student" class="com.zq.student" init-method="myInit" />
Copy the code

Detail analysis

1.Implement InitializingBean and define your own execution order?1.InitializingBean interface2.Custom initialization2.Injection must occur before initializationpublic class student implements InitializingBean {
    private String name;
    public String getName(a) {
        return name;
    }
    public void setName(String name) {
        System.out.println("Student set method");
        this.name = name;
    }
    public student(a) {
        System.out.println("Parameterless construction of student classes");
    }
    @Override
    public String toString(a) {
        return "Student";
    }
    @Override
    public void afterPropertiesSet(a) throws Exception {
        System.out.println("Initialization method");
    }
    public void myInit(a){
        System.out.println("My own method of initialization.");
    }
}
 <property name="name" value="Zhang"></property>
ClassPathXmlApplicationContext s1 = new ClassPathXmlApplicationContext("application.xml"); Console output: student class with no arguments constructor Student set method initializer method I define my own initialization method3.What is initialization initialization of operational resources: network IO database......Copy the code

Third destruction stage

DisposableBean interfaces

// Override the method
@Override
public void destroy(a) throws Exception {
    System.out.println("Method of Destruction");
}
ClassPathXmlApplicationContext s1 = new ClassPathXmlApplicationContext("application.xml");
s1.close();// Close the factory and execute the destruction method
Copy the code

Custom methods

1.Not applicable to scope="prototype"
2.IO. Close () connection.close(); IO.Copy the code

Conclusion:

The Spring container can manage the life cycle of beans under the Singleton scope, where Spring knows exactly when a bean is created, initialized, and destroyed. For prototype-scoped beans, Spring is only responsible for creation. When the container creates an instance of the bean, the bean instance is handed over to the client’s code management and the Spring container no longer tracks its life cycle. It does not manage the life cycle of beans that are configured to prototype scope.

There are three general stages

  • Instantiate and assign attributes Instantiation and Populate
  • Initialize the Initialization
  • Destruction of Destruction

Review the first to see the description content, combined with the code in understanding, I believe you better understand the Spring Bean life cycle!