Bean scope in Spring

Table of Contents

1. What is the scope of Bean?

2. @Scope annotation

3. Six scopes of Bean

3.1 singleton singleton mode

3.2 prototype prototype mode

3.3 request

3.4 sessions

3.5 application

3.6 websockets

1. What is the scope of Bean

In the previous learning process, we defined scope as:Limiting the available range of variables in the program, or defining a certain area of variables. However, in Bean, this scope refers to a certain behavior of the Bean in the Spring framework. Next, let’s analyze a case

First create a User class, and at the same time create a Users class to store the User object in Spring. Here, annotations are used, and this method will be adopted in the future.

public class User {
    private String name;
    private int id;
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + ''' +
                ", id=" + id +
                '}';
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
@Component
public class Users {
    @Bean
    public User user() {
        User user = new User();
        user.setName("Public Name");
        user.setId(1);
        return user;
    }
}

There is a requirement here that a developer needs to obtain the object of this User class and change the original “public name” in the User class object to Zhang San, and the original class name cannot be modified!

In this operation, the developer did not directly use the user object to modify its attributes, but created another user1 to receive the user and modify the name attribute in user1.

@Controller
public class UserController1 {
    @Resource
    private User user;
    public void setName() {
        User user1 = user;
        user1.setName("Zhang San");
        System.out.println(user1);
    }
}

Configure the annotation scan path in the Spring configuration file, and then obtain the class object through the factory provided by Spring. Through testing we found that it was successful.

@Test
public void test() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
    UserController1 userController1 = ctx.getBean("userController1", UserController1.class);
    userController1.setName();
} 

According to the idea, the original user class should not be modified here, but suddenly one day another developer needs to obtain the contents of the original user class.

@Controller
public class UserController2 {
    @Resource
    private User user;
    public void getUser() {
        System.out.println(user);
    }
}
public void test() {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
    //Here is the first developer's
    UserController1 userController1 = ctx.getBean("userController1", UserController1.class);
    userController1.setName();
    // second developer's
    UserController2 userController2 = ctx.getBean("userController2", UserController2.class);
    userController2.getUser();
}

When testing here, you will find that there is a problem. The name in the original class has also been modified. In fact, this is what we call the scope of the Bean. Because the default scope of the Bean is Singleton >, so only one object will be created here!

2. @Scope annotation

How do we solve the above problems? We introduce a new annotation @Scope here to set the scope of the Bean. Here we set the scope of the Bean to the “prototype” prototype mode (multiple instance mode)

@Component
public class Users {
    @Bean("user")
    @Scope("prototype")
    public User user() {
        User user = new User();
        user.setName("Public Name");
        user.setId(1);
        return user;
    }
}

Running the test program again, we found that the problem was solved

In addition to directly writing the scope, @Scope also provides a way to add a scope: using enumeration settings. This method is equivalent to directly writing the domain name.

@Component
public class Users {
    @Bean("user")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public User user() {
        User user = new User();
        user.setName("Public Name");
        user.setId(1);
        return user;
    }
}

3. The 6 scopes of Bean

3.1 singleton singleton mode

Description: The Bean under this scope has only one instance in the IoC container: get the Bean (that is, through
ApplicationContext.getBean and other methods to obtain) and assembly Bean (that is, through @Autowired annotation) are the same object

Scenario: Normally, beans in this state use this scope. ?Status indicates that the property status of the Bean object does not need to be updated.

Note: Spring selects this scope by default

3.2 prototype prototype mode

Description: Each request for a Bean under this operation domain will create a new instance: obtaining the Bean (that is, obtaining it through applicationContext.getBean and other methods) and assembling the Bean (that is, through @Autowired annotation). ) are new object instances.
Scenario: Usually stateful beans use this scope.

3.3 request

Description: Each http request will create a new Bean instance, similar to prototype
Scenario: A shared bean for http requests and responses
Remarks:Limited to use in SpringMVC?

3.4 session

Description: In each http session, define three Bean instances
Scenario: Shared Bean for user reply, such as: recording the login information of each user
Remarks:Limited to use in SpringMVC?

3.5 application

Description: In each http servlet Context, define three Bean instances
Scenario:Contextual information of Web application, for example: recording shared information of two applications
Remarks:Limited to use in SpringMVC?

3.6 websocket

Description: In the life cycle of an HTTP WebSocket, define two Bean instances. Scenario: In each session of the WebSocket, the header information of the Map structure is saved and will be wrapped in the client in the future. Message header. After the first initialization, it is the same Bean until the end of WebSocket.
Note: Limited to Spring WebSocket?

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138,350 people are learning the system

syntaxbug.com © 2021 All Rights Reserved.