The scope of beans in Spring and the Spring life cycle

From the previous article, we can see that Spring is used to store and read beans, so beans are the core resources in Spring, so we will have a deep understanding of beans.

Bean scope

Now there is a public Bean, which is provided to two users to use, but in the process of use, user 1 modifies the public Bean data, when user 2 is using it, it is found that a logical error has occurred.

Our expected result is that public beans can be modified in their respective classes, but do not affect other classes.

the case

Public Bean:


@Controller
public class Users {
    @Bean
    public User getUser() {
        User user = new User();
        user.setId(1);
        user.setName("张三");
        return user;
    }
}

It can be seen that the name at this time is Zhang San.

When user 1 is using it, he has modified it:

@Controller
public class UserController {
    @Autowired
    private User user1;

    public User getUser1() {
        User user = user1;
        System.out.println("修改之前name="+ user1.getName());
        user1.setName("李四");
        return user1;
    }
}

User 2 goes to use the public bean:

@Controller
public class UserController2 {
    @Autowired
    private User user2;

    public User getUser2() {
        User user = user2;
        return user;
    }
}

Then we print the values ​​of user 1 and user 2 public beans at this time:

public class start {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = context.getBean("userController", UserController.class);
        System.out.println(userController.getUser1().toString());

        UserController2 userController2 = context.getBean("userController2", UserController2.class);
        System.out.println(userController2.getUser2().toString());
    }
}

 We found that user 2 actually used the modified bean of user 1 when using the bean.

Cause Analysis

The reason for this is that the bean works in the singleton state by default, which means that everyone uses the same bean. This is because the singleton pattern greatly improves performance, so the scope of the bean in Spring is the default singleton pattern (singleton).

scope definition

Limiting the visible range of variables in a program is called scope, and the scope of a bean refers to a certain behavior pattern in the entire framework of Spring, such as the singleton singleton scope, which means that the bean has only one copy in the entire Spring and is shared globally. When someone else modifies the bean, what the other person reads is the modified value.

Bean scope type

  1. Singleton scope singleton
  2. prototype scope prototype
  3. Request scope request
  4. session scope session
  5. global scope application
  6. HTTPWebSocket scope Websocket

Note: Of the 6 scopes above, only the first two are applicable to Spring common projects, and the other 4 are applicable to Spring MVC projects.

singleton scope

The singleton scope is the default scope. The scope of the public Bean in the code we wrote above is the singleton scope, so the above problems will occur.

prototype scope

For the Bean under this scope, a new instance will be created every time the Bean is acquired.

We can modify the above code and change the scope type to prototype mode, and we will find that the above problem is solved.

 Use @Scope("prototype") to modify the scope

@Controller
public class Users {
    @Bean
    @Scope("prototype")
    public User getUser() {
        User user = new User();
        user.setId(1);
        user.setName("张三");
        return user;
    }
}

 problem solved.

The remaining 4 scopes are only applicable to SpringMVC projects, so I won’t go into details here.

Spring execution process

Start the container    

Initialize according to the configuration file Bean

 During the process of loading the configuration file, the Spring annotations under the com.java.domo package will be scanned, that is, five types of annotations. Only the classes under this package and the classes annotated with the five major categories will be registered in the Spring container.

Register the bean into the container

The above classes are all annotated with 5 categories, so all 5 of these classes will be registered in the container.

Assembly Bean Properties

If the Bean object needs other Bean objects as properties, you can use @Autowired or @Resource

 Bean execution process

Start the Spring container --> instantiate the Bean (allocate memory space, from scratch) --> register the Bean in Spring (save operation) --> assemble the Bean into the required class (fetch operation).

Bean life cycle

The so-called life cycle is the whole process of an object from birth to destruction. We call this process the life cycle of an object.
Bean's life cycle is divided into 5 parts:

  1. Instantiate Bean (allocate memory space for Bean)
  2. Set properties (Bean injection and assembly)
  3. Bean initialization   
  4. use beans    
  5. destroy beans

The third step is to implement various Aware notification methods in Bean initialization.

  • Perform various notifications
  • Execute the pre-initialization method
  • initialization method
  • post-initialization method

Guess you like

Origin blog.csdn.net/qq_63525426/article/details/131863933