Scope and life cycle of Bean in Spring

Keywords: Java Spring

Scope and life cycle of Bean in Spring

Scope

singleton

The default scope in Spring is singleton, that is, singleton mode.

The bean tag attribute in the xml configuration file can omit the configuration of scope="singleton".

For the same implementation class, no matter how many times the getBean() method is called, only one bean object will be produced.

For example, the following code:

// Create an interface
public interface UserDao {
    public void say();
}
// Create an implementation class for the interface
public class UserDaoImpl implements UserDao {

    @Override
    public void say() {
        System.out.println("userDaoImpl say ...");
    }
}

When writing an xml configuration file, you can omit the scope attribute by default because it is a singleton instance by default.

You can also specify the scope by annotation@ scope("singleton")

<?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">


    <!-- The default is scope="singleton"´╝îIt can be omitted -->
    <bean class="top.lukeewin.scope.UserDaoImpl" id="user" scope="singleton"></bean>
</beans>
// Create test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SingletonTest {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean01.xml");
        UserDao user = (UserDao) ctx.getBean("user");
        UserDao user2 = (UserDao) ctx.getBean("user");
        System.out.println(user == user2);
        user.say();
    }
}

Operation results:

From the running results, it can be concluded that when the scope is defined as a singleton, only one instance will be generated, and the instance is generated by the Spring container and managed by Spring.

prototype

Prototype mode. In this mode, it will only be created by Spring, and the management will be handed over to the customer code.

The scope attribute value of the bean tag in the xml configuration file is proptype. In this mode, each bean object obtained will be recreated.

The code is as follows:

I only write the configuration file here, and the others are the same as the above code.

Add some code on the original basis

You can also specify the scope by annotation: @ scope("prototype")

<bean class="top.lukeewin.scope.UserDaoImpl" id="userDao" scope="prototype"></bean>

Then write the test class

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SingletonTest {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean01.xml");
        // singleton
        UserDao user = (UserDao) ctx.getBean("user");
        UserDao user2 = (UserDao) ctx.getBean("user");

        // prototype
        UserDao userDao = (UserDao) ctx.getBean("userDao");
        UserDao userDao2 = (UserDao) ctx.getBean("userDao");

        System.out.println(user == user2);
        System.out.println(userDao == userDao2);
        user.say();
    }
}

Operation results:

From the running results, it can be concluded that different from singleton, when the scope is defined as prototype, the Bean instances obtained each time are different. And it is generated by Spring, but after it is generated, it is not managed by Spring, but handed over to customer code management.

request

When the scope of a bean is request, it means that in an HTTP request, a bean definition corresponds to an instance; That is, each HTTP request will have its own bean instance, which is created according to a bean definition. This scope is only valid in the case of web-based Spring ApplicationContext.

session

When the scope of a bean is session, it means that in an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based Spring ApplicationContext.

globalSession

When the scope of a bean is globalSession, it means that in a global HTTP Session, a bean definition corresponds to an instance. Typically, it is only valid when using portlet context. This scope is only valid in the case of web-based Spring ApplicationContext.

life cycle

Instantiation process of Bean in Spring:

Bean lifecycle:

The execution process of Bean instantiation life cycle is as follows:

  • Spring instantiates beans. The default bean is a singleton;
  • Spring performs dependency injection on bean s;
  • If the bean implements the BeanNameAware interface, Spring passes the bean name to the setBeanName() method;
  • If the bean implements the BeanFactoryAware interface, Spring will call the setBeanFactory() method to pass in the BeanFactory instance;
  • If the bean implements the ApplicationContextAware interface, its setApplicationContext() method will be called to pass the reference of the application context into the bean;
  • If the bean implements the BeanPostProcessor interface, its postProcessBeforeInitialization() method will be called;
  • If the @ PostConstruct annotation is added to a method in the bean, the method will be called;
  • If the bean implements the InitializingBean interface, spring will call its afterpropertieset () interface method. Similarly, if the bean declares the initialization method using the init method property, the method will also be called;
  • If the initialization method is specified through the init method element of the tag in the xml file, the method will be called;
  • If the bean implements the BeanPostProcessor interface, its postProcessAfterInitialization() interface method will be called;
  • At this point, the bean s are ready to be used by the application, and they will stay in the application context until the application context is destroyed;
  • If the @ PreDestroy annotation is added to a method in the bean, the method will be called;
  • If bean implements DisposableBean interface, spring will call its destroy () interface method. Similarly, if the bean declares a destroy method using the destroy method attribute, the method is called;

When scope="singleton", by default, it will be instantiated and fully initialized when the Spring container starts. If you want to delay initialization, you can use lazy init = "true" to delay initialization.

For the ableBean interface, spring will call its destroy () interface method. Similarly, if the bean declares a destroy method using the destroy method attribute, the method is called;

When scope="singleton", by default, it will be instantiated and fully initialized when the Spring container starts. If you want to delay initialization, you can use lazy init = "true" to delay initialization.

When scope="prototype", by default, it will only be instantiated and not initialized, but only initialized when requesting beans. At the first request for every prototype bean, the Spring container calls its constructor to create the object and then calls the method specified in the init-method attribute value. When the object is destroyed, the spring container will not call any methods for us, because it is a non singleton. There are many objects of this type. Once the spring container gives you this object, it will no longer manage this object.

Posted by pacholo on Tue, 07 Sep 2021 17:42:32 -0700