SpringBoot notes 01 -- Brief principles of spring IOC

SpringBoot notes 01 – Spring IOC

1. IOC

1.1 what is IOC

The full name of IOC is Inversion of Control, which is a design concept. In the traditional Java SE code, objects are created through new inside an object, which is the program's initiative to create the objects to rely on. The idea of IOC is to design a container to create these objects, and the IOC container controls the creation of objects.

In other words, the original mode is that the program actively controls the required dependent classes, but now the IOC container controls the dependent classes. The program takes the initiative to obtain the class, which is positive. If it is controlled by IOC, it is reverse. The IOC container will help us find and inject dependent objects. Objects are only passive to accept dependent objects. Such a process is inversion.

1.2 why IOC

In traditional code design, the upper class depends on the lower class. For example, to make a hamburger, we need bread slices, vegetables, meat and so on. The traditional implementation method requires us to instantiate the required ingredients one by one in the hamburger class and then put them together, but this method is not very friendly to subsequent maintenance, because once we update the recipe, for example, I want to eat pork hamburger or I want to eat double-layer hamburger, then I have to find new ingredients, You need to modify the original code. IOC is equivalent to that I no longer make hamburgers by myself. There is an additional chef between me and hamburger. I tell the chef what kind of hamburger I want, and then the chef will find the corresponding ingredients to cook for me. For me, I'm only responsible for telling the chef what I want, and then silently waiting for the hamburger.

2. DI (Dependency Injection)

When the IOC container is running, it will dynamically provide the objects it needs to an object, which is realized through dependency injection. The so-called dependency injection is the process in which the chef makes the hamburger for me. I don't need to know how the chef finds the ingredients and how to make the hamburger. I'm just responsible for eating.

Talk is cheap,show me your code

The following is a simple demo based on Spring. I hope this demo can well explain a role of Spring IOC.

Define a Source class to represent the ingredients we want

public class Source {
    private String bread;
    private String vegetables;;
    private String meat;
    private int size;

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getBread() {
        return bread;
    }

    public void setBread(String bread) {
        this.bread = bread;
    }

    public String getVegetables() {
        return vegetables;
    }

    public void setVegetables(String vegetables) {
        this.vegetables = vegetables;
    }

    public String getMeat() {
        return meat;
    }

    public void setMeat(String meat) {
        this.meat = meat;
    }
}

Then define a Cooker class to represent a cook between us and hamburger

public class Cooker {
    private Source source = null;

    public Cooker(){
        System.out.println("This is Cooker Nonparametric structure of");
    }

    public String makeHamburgers(){
        return "This is a"+source.getMeat()+","+source.getVegetables()+"as well as"+source.getBread()+"Composed"+source.getSize()+"Layer hamburger";
    }

    public Source getSource() {
        return source;
    }

    public void setSource(Source source) {
        this.source = source;
    }
}

According to the default writing method of Spring, we need to write an xml configuration file and write down the contents we want to set in the file. In this file, we can set some contents we want to set, such as the id, class and other attributes of Bean, and whether it is a singleton mode. Let's just write some simple usage here.

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- more bean definitions go here -->

 
    <bean id="source" class="com.Services.Source">
        <property name="bread" value="Thick bread slice"/>
        <property name="meat" value="beef"/>
        <property name="vegetables" value="tomato"/>
        <property name="size" value="2"/>
    </bean>

    <bean id="cooker" class="com.Services.Cooker">
        <property name="source" ref="source"/>
    </bean>

</beans>

Create a test class and implement a test function in it to see if it is implemented correctly

 @Test
    public void should_get_correct_result() {
        // Indicate the address of the configuration file, which is in the resource directory by default
        String config = "beans.xml";
        // Get profile content
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
        Cooker cooker = (Cooker) applicationContext.getBean("cooker");
        String res = cooker.makeHamburgers();
        System.out.println(res);
    }
// Output:
// This is the parameter free construction of Cooker
// This is a 2-layer hamburger made of beef, tomato and thick bread slices

As you can see, our program successfully executes the method makeHamburgers().

Let's take a further look at how the program runs inside the original Spring writing method.

IOC part:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config) this step is to instantiate the container, which will automatically pre initialize all Bean instances. It can also be seen from the above running results that before running the makeHamburgers method, there is an additional parameter free structure of the Cooker, which is an example of container pre initialization. ApplicationContext instantiates all singleton beans by default. Then use the getBean method to get the required dependencies. The name here corresponds to the id previously taken in the xml file.

DI part:

The IOC container will inject the dependent instance through the setter method of the attribute, such as < property name = "bread" value = "thick bread" / > setting the value through the method of obtaining the attribute name and, of course, in the form of type, which will not be repeated here.

To be continued

Keywords: Java Spring Spring Boot ioc

Added by Wabin on Tue, 08 Mar 2022 06:12:49 +0200