Scope of Bean in Spring

  When instantiating through the Bean tag in the Spring container, you can also specify the scope of the Bean and set it with scope="".

range Function description
singleton The default scope in Spring is a singleton mode, and there will only be one instance of bean definition in the IOC container
prototype In many cases, each time the getBean() method is called to obtain the scope of the bean tag as prototype, a new instance will be generated
request Applied in a web project, after Spring creates this class, it will be stored in the request scope
session Applied in a web project, after Spring creates this class, it stores this class in the session scope
globalsessio Applied in a web project, it must be used in a portlet environment. But if there is no such environment, relative to session

Singleton mode (default mode):

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="singleton"></bean>

Prototype mode (multiple cases):

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="prototype"></bean>

We use the code in the previous article to test these two modes:
  bean.xml is configured as a singleton mode when configuring the bean tag:

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="singleton"></bean>

  Run the test code:

public class TestDemo01 {
    
    
    public static void main(String[] args) {
    
    
        //加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //根据bean标签的id获取实例对象
        UserService userService1 = (UserService) context.getBean("userService");
        UserService userService2 = (UserService) context.getBean("userService");
        //调用方法
        userService1.saveUser();
        System.out.println(userService1);
        System.out.println(userService2);
        System.out.println(userService1 == userService2);
    }
}

Operation result: It
Insert picture description here
  can be seen that the address of the object is the same when printed twice.
 When configuring bean tags in bean.xml, configure them as prototype mode:

<bean id="userService" class="com.zy.service.impl.UserServiceImpl" scope="prototype"></bean>

Continue to run the above test code, the results are as follows: It
Insert picture description here
can be seen that the addresses of the two objects printed are not the same.

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/111013651