Deep understanding of SpringIOC



The article has been hosted on GitHub . You can check it out on GitHub. Welcome bosses to Star!
Search and follow the WeChat public number and get Offer to receive various learning materials!

Deep understanding of Spring IOC (Inversion of Control)


1. IOC overview

Inverse Of Controll is the inversion of control, or IOC for short .

To put it simply, IOC reverses the way of satisfying the dependency relationship, from creating dependent objects before, to being pushed by the factory. (Change from active to passive, that is, reverse) It solves the strong coupling between components with dependencies, making the project form more robust

2. What is IOC?

2.1 Understanding IOC thinking

I probably understand that IOC is an inversion of control, but now we don't know its thought and function. So the question is, what is IOC (Inversion of Control)?

Inversion of Control, IOC for short. As the name suggests, it is a combination of the words "control" and "reverse". Then we will follow the vine and analyze these two words separately!

2.2 Control

The word control, we need to think about a lot. For example, the conditions for achieving control must be two objects . Control can be divided into who controls who and what you do . Then we enumerate these situations one by one:

  1. In Java, we create objects in the new way. Developers control the development tools and indirectly control the dependent objects needed for program creation. For the program, it directly controls the creation of objects; what about IOC? That can be the IOC container directly controls the creation of objects
  2. Since it is the IOC that controls the creation of the object, how does it control the creation of the object? Using IOC to create objects requires tags to introduce external objects, which shows that the IOC container controls the entry of creating dependent objects

2.3 Reverse

We also think a lot about the word reversal. For example, the conditions for achieving a reversal must be two objects . If there is a reversal, there will be a forward rotation , and then something is reversed . Then we also enumerate one by one:

  1. In Java we are an indirect utility to create objects, which can be regarded as forward rotation. With the IOC container, it changed all at once. We don’t need to create new objects ourselves, but directly inverted to create dependent objects and store them in the IOC container.
  2. To use the IOC container to create an object, we only need to tell it what the object needs to be created through the configuration, and identify what will be used in the future to obtain the object created in the IOC container (the process of configuring the IOC container), then wait for you If you want the object in the IOC container, just use this unique identifier to obtain it, and the process of obtaining must be that the IOC uses this unique identifier to find and return the object to us
  3. Maybe some friends still don't understand the reversal. Why is the behavior of the IOC container helping us create objects called inversion? Because the container helps us find and inject dependent objects, the objects just passively accept dependent objects. What if it is not reversed? The developer needs to create an object, and find, obtain, and use the object, and everything in this process is controlled by the developer

Three, the role of IOC

Through inversion of control, when an object is created, an external entity that regulates all objects in the system passes the reference of the object it depends on to it. It can also be said that the dependency is injected into the object.

For example, the object b of Class B is used in Class A. In general, you need to explicitly new a B object in the code of A.

What about after using IOC? The code of A only needs to define a private B object. It does not need to be directly new to obtain this object. Instead, the B object is externally new and injected into the reference in the A class through the relevant container control program. The specific acquisition method and the state of the object when it is acquired are specified by the configuration file (xml)

Since the object relationship is specified by the configuration file, it greatly reduces the strong coupling between the components and facilitates maintenance, making the project more robust and flexible

Fourth, IOC solves the strong coupling between Dao layer and Service layer

In the original Web development, the Dao layer and the Service layer are inseparable. The Dao layer is the data access layer and only deals with the database. The Servcie layer is the business processing layer, which only processes and implements the corresponding business. When we string together the Dao layer and the Service layer in Web development, we need a new private Dao layer implementation object (XxxDaoImpl) in the Service layer. With the idea of ​​IOC, thinking about the implementation of the traditional Dao layer and Service layer is very inflexible. Once the Dao layer implementation class is modified, the source code in the project must be modified. Obviously it is very scary. thing.

5. Use IOC to solve the strong coupling between Dao layer and Service layer

Since it solves the strong coupling between the Dao layer and the Service layer, these two components are necessary, right?

Dao layers

// Dao层接口
package com.mylifes1110.dao;

import com.mylifes1110.bean.User;

public interface UserDao {
    
    
    int insertUser(User user);
}

// Dao层实现类
package com.mylifes1110.dao.impl;

import com.mylifes1110.bean.User;
import com.mylifes1110.dao.UserDao;

public class UserDaoImpl implements UserDao {
    
    

    @Override
    public int insertUser(User user) {
    
    
        System.out.println("------insertUser and UserDao------");
        return 0;
    }
}

Note: When we use IOC, we must inject Dao layer implementation class objects into the IOC container. There must be an injection method to tell the IOC container to create and obtain objects. In the Service layer, we don’t need new implementation class objects. It is to create a Setter method of the Service layer to inject UserDaoImpl dependencies into UserServcieImpl (you can think of them as assembly here). The injection method used at this time is called Setter method dependency injection. Now there is no need to tangle, I will inject all dependencies in the future. Ways to enumerate and analyze dependency injection ideas and the relationship between dependency injection and IOC.

Service layer

// Service层接口
package com.mylifes1110.service;

import com.mylifes1110.bean.User;

public interface UserService {
    
    
    int insertUser(User user);
}

// Service层实现类
package com.mylifes1110.service.impl;

import com.mylifes1110.bean.User;
import com.mylifes1110.dao.UserDao;
import com.mylifes1110.service.UserService;

public class UserServiceImpl implements UserService {
    
    
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }

    @Override
    public int insertUser(User user) {
    
    
        System.out.println("------insertUser and UserService------");
        return userDao.insertUser(null);
    }
}

spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
       http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd">

	<!--id:唯一标识 class:需要被创建的目标对象全限定名-->
	<bean id="UserDao" class="com.mylifes1110.dao.impl.UserDaoImpl"/>
        
	<!--id:唯一标识 class:需要被创建的目标对象全限定名-->
    <bean id="UserService" class="com.mylifes1110.service.impl.UserServiceImpl">
        <!--Setter方法依赖注入 name:Service层定义的userDao属性 ref:Dao层bean标签唯一标识-->
        <property name="userDao" ref="UserDao"/>
    </bean>
        
</beans>

Test class

/**
* @MethodName insertUser1
* @Param []
* @Description 测试IOC的使用
* @Author Ziph
* @Date 2020/7/12
*/
@Test
public void insertUser1() {
    
    
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    UserService userService = (UserService) context.getBean("UserService");
    userService.insertUser(null);
    // 打印结果
    ------insertUser and UserService------
    ------insertUser and UserDao------
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44170221/article/details/107305601