Probe into Spring's IOC container

Probe into Spring's IoC container

This blog is suitable for readers who already know how to use spring, not beginners. The blogger here will also use a step to think about why it can be used in the future. I want to go deep into the bottom layer, but obviously it cannot be called deep hhh.

IoC concept

IoC (Inverse of Control) literally means inversion of control. It is responsible for managing the creation of objects and the calls between objects through Spring, with the purpose of reducing program coupling. Then there are two words here, control and inversion, let us take two words into the learning of IoC container.

Call between objects

Insert picture description here

When we use another object in one object, we must explicitly create an instance of another object, whether it is a constructor method or a factory method (the factory method is actually new) to obtain the object.

There are three ways to call between objects

1. Calling methods of traditional java objects

class UserSerivce{
    
    
    addUser(){
    
    
        UserDao dao = new UserDao();
        dao.add();
    }
}
class UserDao{
    
    
    add(){
    
    
        System.out.println("add");
    }
}

Here, if the method in our UserDao changes, the code in UserService will obviously also change.

2. Factory model

class UserService{
    
    
    void add(){
    
    
        UserDao dao = UserFactory.getUserDao();
    }
}
class UserDao{
    
    
    add(){
    
    
        //*****
    }
}
class UserFactory{
    
    
    public static UserDao getUserDao(){
    
    
        return new UserDao();
    }
}

3. It is the IoC we are going to look at today

Use IoC to create

Three technologies used at the bottom of IoC

  • xml parsing
  • Factory mode
  • reflection

IoC process

1#Create xml configuration class, configure the created object

<bean id="userDao" class="com.feng.UserDao">
</bean>

2#Create factory class, use reflection mechanism to create object

class UserFactory{
    
    
    public static UserDao getUserDao(){
    
    
        String classValue = class属性值;
        //利用xml解析xml文件中的class属性来获取class值com.feng.UserDao
        Class clazz = Class.forName(classValue);
        return (userDao)clazz.newInstance();
    }
}

It can be found that Spring's IoC method minimizes the coupling between programs, and the creation of objects and scheduling between objects can be thrown to Spring for management.

Spring IoC container

The idea of ​​IoC is based on the container. The bottom layer of the IoC container is actually an object factory. To instantiate the container, Spring provides us with two ways (two interfaces).

BeanFactory:

BeanFactory provides basic functions for IOC containers. As mentioned in the Spring documentation, this class is currently only for backward compatibility with older versions. Unless you have to use it, you should use the second container.

etc:

	BeanFactory beanFactory = new ClassPathXmlApplicationContext("bean1.xml");
//加载配置文件不创建对象
	User user = beanFactory.getBean("user",user.class);
//此时才创建对象

ApplicationContext:

You can know from the API document that ApplicationContext is a sub-interface of BeanFactory, and from the document you can also see that ApplicaionContext not only contains all the functions of BeanFactory but also supports more functions.

etc:

ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");//加载配置文件时,创建对象 
User user = context.getBean("user",User.class);

Insert picture description here

You can see that there are many implementations of ApplicationContext, the two commonly used are not unfamiliar to everyone.

FileSystemXmlApplicationContext:默认是从系统的盘符下获取文件 
ClassPathXmlApplicationContext:默认是指项目的classpath路径下面的配置文件

IoC alias, dependency injection

Dependency Injection (DI, Dependency Injection)

The so-called dependency injection is that the IOC container dynamically injects a certain dependency into the object during the runtime. Why IoC is also called DI? In fact, they just describe one thing from a different perspective, that is, by introducing IoC containers and using dependency injection to achieve decoupling between objects.

Here is an easy-to-understand example. For example, there are two objects, object A and object B. Now A wants to call B. Does it need an IoC container? We regard A as a computer, and B may be a mouse, a keyboard, a hard disk, and a USB flash drive. Anyway, it can be plugged into the computer and used for the computer. The computer (object A) now needs a USB flash drive (object B) Who is the IoC container? You are the IoC container, what have you done? You can plug in whatever the computer wants to use. After plugging in, he will have control of Object B (either by reading the USB flash drive or connecting the mouse). You (the IoC container is only responsible for satisfying him), he doesn’t need to worry about how to create the mouse and keyboard (creating objects) or how to destroy it. Anyway, you (IoC) take care of everything, is it great? understanding.

Now I need a USB flash drive (object B), who is the IoC container? You are the IoC container, what have you done? You can plug in whatever the computer wants to use. After plugging in, he will have control of Object B (either by reading the USB flash drive or connecting the mouse). You (the IoC container is only responsible for satisfying him), he doesn’t need to worry about how to create the mouse and keyboard (creating objects) or how to destroy it. Anyway, you (IoC) take care of everything, is it great? understanding.

In traditional implementation, object A has to be new by itself, and the coupling between various components is very serious. With the IoC container, it brings the relationship between components from the inside of the program to the external container, which means that the container dynamically injects a certain dependency between components into the component during runtime.

SpringIoC example

Entity class

public class Hello {
    
    
    private String name;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}

beans.xml

<?xml version="1.0" encoding="GBK"?>
<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">

    <!--使用Spring来创建对象,在Spring这些都成为Bean

        类型  变量名 = new 类型();
        Hello hello = new Hello();

        id = 变量名
        class = new 的对象
        property 相当于给对象的属性设置一个值
        
        ref:引用Spring容器中创建好的对象
        value:具体的值,基本数据类型
    -->
    <bean id="hello" class="com.feng.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

</beans>

Test class

public class MyTest {
    
    
    public static void main(String[] args) {
    
    
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml");
        //我们的对象现在都在Spring中管理,我们要使用直接去里面取出来即可
        Hello hello = (Hello)context.getBean("hello");
        System.out.println(hello.toString());
    }
}

Guess you like

Origin blog.csdn.net/weixin_43876186/article/details/108600153