A popular explanation of how IOC in spring solves the dependencies between classes (implemented by building a self-built beanFactory class)

1. Introduction

  Friends who are new to Spring must be very confused about the term ioc. When you search for what is ioc on Baidu, this is the explanation of the Baidu entry:

Inversion of Control (IoC) is a design principle in object-oriented programming that can be used to reduce the coupling between computer codes.

So what the hell is IOC? ? How can it reduce the coupling between codes?
This article will take you step by step to understand how IOC solves this problem from the most basic case.
Friends, please open the idea and try it out together!

2. Case 1: Program with high coupling degree

  As shown in the figure below, we created a project in idea.
  The basic logic of this project is that the presentation layer calls the service layer, the service layer calls the dao layer, and the dao layer operates the database.Insert image description here

We will naturally inject the service layer class into the presentation layer, and the service layer injects the Dao layer class to implement method invocation. like this

Presentation layer:
Insert image description here

Service layer:
Insert image description here
However, this method of injecting objects will cause a serious problem:
The presentation layer depends on the service layer, and the service layer depends on the Dao layer.

If we delete the classes in the Dao layer, then the project will report an error and it will be impossible to even compile!!
Insert image description here

2.1 Solution to Case 1: Use reflection to create objects for us

  In order to avoid the problem of too high coupling, we will write a BeanFactory ourselves to create objects reflectively, soEven if the object does not exist, no error will be reported when writing code.

public class BeanFactory {
    
    
    //定义一个Properties对象
    private static Properties props;


    private static Map<String,Object> beans;

    //使用静态代码块为Properties对象赋值
    static {
    
    
        try {
    
    
            //实例化对象
            props = new Properties();
            //获取properties文件的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            //实例化容器
            beans = new HashMap<String,Object>();
            //取出配置文件中所有的Key
            Enumeration keys = props.keys();
            //遍历枚举
            while (keys.hasMoreElements()){
    
    
                //取出每个Key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器中
                beans.put(key,value);
            }


        }
        catch(Exception e){
    
    
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
    }

    /**
     * 根据Bean的名称获取bean对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
    
    

        return beans.get(beanName);
    }
  }

2.2 Explanation of beanFactory

  In the beanFactory we wrote ourselves, we create the object through reflection of the fully qualified class name of the object, and then store it in the map collection .

  When we need an object, we only need to pass in the name of the object we want to create through the getBean method, and then find the fully qualified class name corresponding to the object name in the pre-written properties. Finally reflection creates the object.

//.properties文件
accountService=com.eric.service.impl.AccountServiceImpl
accountDao=com.eric.dao.impl.AccountDaoImpl
//反射创建对象
  Object value = Class.forName(beanPath).newInstance();

3. Improvement of Case 1: Use beanFactory to create objects

Insert image description here

Insert image description here

4. Summary:

  You can compare the improvements in Case 1 with Case 1. If at this time youDelete the Dao layer code. The service layer and presentation layer will not report errors.

Doesn't this reduce the dependency between classes?

  The actual spring also does this, that is, giving control of the object to spring's ioc container, without requiring us to manually new the object

  We package the object into a bean object and hand it over to the IOC container for management. This is the definition of IOC – Inversion of Control.

Guess you like

Origin blog.csdn.net/qq_44716086/article/details/105918818