Easy to understand-dependency injection

The core of spring is a lightweight inversion of control (IOC) and aspect-oriented programming (AOP) framework!
The inversion of control is to reduce the coupling between codes, the most common way is dependency injection

What is dependency injection?

Let's first look at what dependency is. In life, relying on others or other things without being able to be independent or independent is called dependence.

So what is dependency in application? Dependency refers to the relationship between two instances. One instance is independent, and the other instance is dependent (dependent), and it depends on another instance. For example, the computer object, which contains the host object and the display object. If there is no host object or display object, the computer object is incomplete and cannot be used normally. We say that the computer object depends on the host object and the display object.

So what is injection? Computer objects are inseparable from the host object and the display object. When the program is running, we must provide the computer object with the host object and the display object it needs, and provide the host object and the display object to the computer object like a "injection". The process is called injection. In other words, if an object needs another object to be used normally, we provide the object with the object it needs when the program is running. This is called "dependency injection".

We know that Spring will manage almost all Bean objects, and there may be dependencies between objects. During the running of the program, Spring assembles all the objects we need. This is Spring's dependency injection. In traditional Java design, when a caller of a Java instance creates a called Java instance, the called Java class is required to appear in the caller's code, and loose coupling cannot be achieved between the two. In layman's terms, the factory model has improved this, so that the caller does not need to care about the specific implementation process of the callee, and can use it as long as it obtains an instance that meets a certain standard (interface). The calling code is oriented to interface programming, which supports the decoupling of the caller and the callee, so the factory pattern can be widely used. But in the factory model, the caller needs to locate the factory by himself and be coupled with the specific factory, so the decoupling of the caller and the callee is only achieved to a certain extent. With the emergence of Spring, the caller does not need to locate the factory by himself. When the program runs to the callee, the system will automatically provide the callee instance. In fact, both the caller and the callee are managed by Spring, and the dependency between the two is provided by Spring.

In layman's terms: the class B object is used in class A. Under normal circumstances, a new B object in class A needs to be used. Dependency injection only needs to define a private B object in class A.

Dependency injection, an aspect of IOC, is a common concept, and it has many explanations. The concept is that you don't need to create an object, but only need to describe how it is created. You don't assemble your components and services directly in the code, but you need to describe which components need which services in the configuration file, and then a container (IOC container) is responsible for assembling them.

Comprehensive case of dependency injection
  • How to develop a printer?
    Can be flexibly configured to use color ink cartridges or black ink cartridges
    Can flexibly configure the size of the printed page (A4, B5)
    The realization of the printer function depends on the ink cartridge and paper
  • Step
    1. Define the interface standards for ink cartridges and paper
    2. Use the interface standards to develop the printer
    3. Assemble the printer
    4. Run the printer

1. Define the interface standard of ink cartridge and paper

//定义墨盒接口
public interface InkBox {
    
    
    //提供获取颜色的方法
    String getColor();
}
============== 为了阅读方便放在了一起 标准做法应该要分开写 ==============
//定义纸张大小接口
public interface PaperSize {
    
    
    //提供获取纸张大小的方法
    String getPaper();
}

2. The implementation class of the interface

//A4纸张
public class A4Paper implements PaperSize {
    
    
    public String getPaper() {
    
    
        return "A4";
    }
}
//B5纸张
public class B5Paper implements PaperSize {
    
    
    public String getPaper() {
    
    
        return "B5";
    }
}
//黑色墨盒
public class BlackInkBox implements InkBox {
    
    
    public String getColor() {
    
    
        return "黑色墨盒";
    }
}
//彩色墨盒
public class ColourInkBox implements InkBox {
    
    
    public String getColor() {
    
    
        return "彩色墨盒";
    }
}

3. Printer class (the class is defined here, if you want to assemble different printers, you have to use the interface, and different printer classes implement a common printer method)

Setter method injection: Setter method injection means that after the container instantiates the bean by calling the parameterless constructor or the parameterless static factory method, the setter method of the bean is called, which realizes the setter-based dependency injection.

public class Printer {
    
    
    private InkBox inkBox;
    private PaperSize paperSize;
	//通过set注入必须要提供无参构造
    public Printer() {
    
    
    }
	//提供setter方法对应xml文件中标签<property name="paperSize" ref="a4Paper"/>
    public void setInkBox(InkBox inkBox) {
    
    
        this.inkBox = inkBox;
    }
    //提供setter方法对应xml文件中标签<property name="inkBox" ref="colourInkBox"/>
    public void setPaperSize(PaperSize paperSize) {
    
    
        this.paperSize = paperSize;
    }
    //组装打印机的方法
    public void print(){
    
    
        System.out.println("使用"+inkBox.getColor()+"打印出了"+paperSize.getPaper()+"大小的纸张");
    }
}

4. Configure the applicationContext.xml file

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

    <!-- 创建A4Paper的对象 -->
    <bean id="a4Paper" class="com.li.bean.Impl.A4Paper"/>
    <!-- 创建ColourInkBox的对象 -->
    <bean id="colourInkBox" class="com.li.bean.Impl.ColourInkBox"/>
    <!-- 创建Printer对象 Printer中用到了PaperSize InkBox 两个接口的引用 所以需要接口的实现类-->
    <bean id="printer" class="com.li.bean.Printer">
        <property name="paperSize" ref="a4Paper"/>
        <property name="inkBox" ref="colourInkBox"/>
    </bean>

    <bean id="b5Paper" class="com.li.bean.Impl.B5Paper"/>
    <bean id="blackInkBox" class="com.li.bean.Impl.BlackInkBox"/>
    <bean id="printer2" class="com.li.bean.Printer">
        <property name="paperSize" ref="b5Paper"/>
        <property name="inkBox" ref="blackInkBox"/>
    </bean>
</beans>

5. Test

public class TestPrinter {
    
    
    /**
     * 一般情况下:new 对象
     */
    @Test
    public void printerOut() {
    
    
        A4Paper a4Paper = new A4Paper();
        ColourInkBox colourInkBox = new ColourInkBox();
        Printer printer = new Printer();
        printer.setPaperSize(a4Paper);
        printer.setInkBox(colourInkBox);
        printer.print();
        //使用黑色墨盒打印出了A4大小的纸张
    }

    /**
     * 创建对象由配置文件管理
     */
    @Test
    public void printerOut2(){
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Printer printer = context.getBean("printer", Printer.class);
        printer.print();
        //使用彩色墨盒打印出了A4大小的纸张
    }

    @Test
    public void printerOut3() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Printer printer = context.getBean("printer2", Printer.class);
        printer.print();
        //使用黑色墨盒打印出了B5大小的纸张
    }
}

Summary: Spring IOC is responsible for creating objects, managing objects (through dependency injection (DI), assembling objects, configuring objects, and managing the entire life cycle of these objects).

Guess you like

Origin blog.csdn.net/lirui1212/article/details/108977147