Spring IOC and Bean scope and life cycle

Directory

1. What is spring IOC?

2. Understanding of IOC/DI

3.Bean scope

4. Bean life cycle

5. Summary of omissions in the previous article


1. What is spring IOC?

The spring container is mainly the implementation of the IOC design pattern. It mainly uses containers to unify management of Bean objects and manage dependencies between objects.

In Spring, we basically don’t need a new class, let Spring do it. When Spring starts, it will instantiate the required classes into objects. If dependencies are needed, the dependencies will be instantiated first, and then the current class will be instantiated. Because dependencies must be passed in through the construction function, when instantiated, the current class will receive and save all dependent objects.
This step is called Dependency Injection.

In Spring, the instantiation of classes, the instantiation of dependencies, and the introduction of dependencies are all controlled by the Spring Bean container, rather than the conventional methods of instantiating objects with new and passing in dependencies through non-constructor methods. The actual control has been transferred to the program management, not the programmer management, so it is called inversion of control.
Spring provides a container, called the IOC container, used to act as the external in the IOC idea
The IOC container is responsible for a series of tasks such as object creation and initialization, and the created or managed objects are collectively called Bean in the IOC container.

2. Understanding of IOC/DI

IoC is the abbreviation of Inversion of Control, which means “inversion of control” when translated into Chinese. It is not a specific technology, but an idea to realize object decoupling.

To explain what is decoupling? It is necessary to understand what coupling is. The so-called **coupling means: there is a dependency between two or more objects, and when one party is modified, it will affect the other, so it is said that there is coupling between these objects. **And decoupling is to remove two or more objects and affect the other party after modification.

DI is the abbreviation of Dependency Injection, translated into Chinese means “Dependency Injection”. Dependency injection is not a design implementation, but a specific technology, which is During the running of the IoC container, the technology of dynamically injecting a dependent object into the current object is called DI (Dependency Injection).

For example: when class A uses class B, it introduces the dependent object B through the construction method. This implementation method can be regarded as a means to achieve dependency injection by through the construction method. The specific code as follows

class A {
    // First define a B object that needs to be depended on
    private B b;
    // realize the assignment through the construction method
    public A(B b) {
        this.b = b;
    }
    public void init() {
        // call the init method in class B
        b.init();
    }
}

From the above content, we can see that although IoC and DI have different definitions, they do the same thing and are used to achieve object decoupling, but the two are different:IoC It is a design idea, while DI is a specific implementation technology.

Let me give you an example and it will become clearer soon: For example, a blogger is in a good mood today and wants to go out for a big meal in the afternoon, then “want to have a big meal” is a kind of thought, which is IOC strong>

But what kind of feast is delicious? Mutton Hot Pot or BBQ Beer? What to eat specifically is DI.

So “the blogger is in a better mood today and wants to go out for a big meal” is a kind of thought, which is IOC, and eating a hot pot instead of barbecue is a concrete realization, which is DI.

3.Bean scope

The scope of a bean refers to a certain behavior pattern of a bean in the entire framework of Spring. For example, the singleton singleton scope means that there is only one Bean in the entire Spring, which is shared globally. When someone modifies this value, another person will read the modified value . For example, if we define a singleton Bean object user in Spring (the default scope is singleton), the specific implementation code is as follows:

@Component
public class UserBean {
    @Bean
    public User user() {
        User user = new User();
        user.setId(1);
        user.setName("Java"); // The key point of this behavior: the user name is Java
        return user;
    }
}

Then, use and modify the user object in class A, the specific implementation code is as follows:

@Controller
public class AController {
    @Autowired
    private User user;
    public User getUser() {
        User user = user;
        user.setName("MySQL"); // The key point of this behavior: modify the user name
        return user;
    }
}

Finally, the user object is also used in class B, and the specific implementation code is as follows:

@Controller
public class BController {
    @Autowired
    private User user;
    public User getUser() {
        User user = user;
        return user;
    }
}

At this time, when we access the getUser method in object B, we will find that the user name at this time is “MySQL” modified in class A, instead of the original “Java”, which means that the bean object user defaults to the singleton scope . If this singleton object is modified anywhere, then other classes will get a modified value when called again.

——————scope classification————————— ————————————-

In Spring, there are five common scopes of beans:

  1. singleton: singleton scope;
  2. prototype: prototype scope (multiple instance scope);
  3. request: request scope;
  4. session: session scope;
  5. application: global scope.

Note: The latter three scopes are only applicable to the Spring MVC framework.

singleton: There is only one instance of the Bean under this scope in the IoC container: the obtained Bean (that is, obtained through methods such as applicationContext.getBean) and the assembled Bean (that is, injected through @Autowired) are the same object.

prototype: Each request for the Bean under the scope will create a new instance: getting the Bean (that is, obtaining it through applicationContext.getBean, etc.) and assembling the Bean (that is, injecting it through @Autowired) are new object instances .

request: Each Http request will create a new Bean instance, similar to prototype.

session: In an Http Session, define a Bean instance.

application: In an Http Servlet Context, define a Bean instance.

4.Bean life cycle

The life cycle of Bean in Spring refers to the whole process from creation to destruction of Bean in Spring (IoC). The life cycle of Bean in Spring mainly includes the following 5 parts:

  1. Instantiation: allocate memory space for the Bean;
  2. Set properties: inject and assemble the Bean properties that the current class depends on;
  3. Initialize:
    1. Execute the pre-method of initialization;
    2. Execute the initialization method;
    3. Post method to perform initialization.
  4. Use Bean: use the Bean object in the program;
  5. Destroy Bean: Destroy the Bean object.

In the above life cycle, it should be noted that:“Instantiation” and “initialization” are two completely different processes. The system level is converted to the user level, and the business code added by the user starts to be executed.

5. Summary of omissions in the previous article

1. The difference between @Autowired and @Resource annotations

(1) @Autowired is an annotation provided by the spring framework, while @Resource is an annotation provided by JDK

(2) @Autowired must be used in the spring framework, otherwise an error will be reported. And @Resource can not be used in the spring framework

(3) It shows that the specified reference to a Bean is used in different ways: @Resource (name=”xxx”), @Autowired combined with @Qualifier

2. How to correctly inject a Bean of the same type into a property