Spring's core mechanism-dependency injection

introduction

       In the previous article, we followed how to use idea to create the first Spring . In the article, Person and Axe have dependencies! So how does Spring manage the relationship between them! !
Insert picture description here

Spring core functions

  • As a super factory, the Spring container is responsible for creating and managing all Java objects. These Java objects are called Beans.
  • The Spring container manages the dependencies between the beans in the container. Spring uses a method called "dependency injection" to manage the dependencies between the beans.

Spring essence

       The essence of Spring: Drive Java code through XML configuration. Familiar with Spring: Almost all Java code is placed in XML to configure. Requirements: The XML configuration you see in your eyes, what you think in your mind is the executed Java code.
       Bean element: The driver uses new to call the constructor. By default it always calls the constructor with no parameters. If you want to control it to call a constructor with parameters, you need to add a
              <constructor-arg.../> sub-element in the <bean.../> element, each of which represents a constructor parameter.
              The value specified by the value attribute in the <constructor-arg.../> child element will be treated as String first. In order to explicitly specify the type of the value, you can specify the type attribute.
       property element: drive it to call the setter method. After the object is created, it will be called immediately.
       The constructor-arg element: The driver calls the constructor with parameters.

Dependency injection

IOC and dependency injection

       The two are two expressions of the same behavior, but the description angle is different! IOC starts from the point of view of the caller. The caller does not need to take the initiative to obtain the dependent object, but is automatically assigned to it by the Spring container. Therefore, the caller has changed from actively obtaining the dependent object to passively accepting it. Dependency injection is from the perspective of the Spring container, which is responsible for assigning dependent objects to member variables of the caller.

Method to realize'

Dependency injection can be divided into three types:

  • Interface injection. rarely use.
  • Setting value injection: It is to call the setter method through the property element control, which is the so-called setting value injection.
  • Constructor injection: Constructor-arg controls to call the parameterized constructor, and the constructor injects the dependent component.

Setpoint injection

public interface Person {
    
    
    //定义一个使用斧头的方法
    public void useAxe();
}

public interface Axe {
    
    
    //Axe接口中定义一个chop()方法
    public String chop();
}

public class Chinese implements Person {
    
    
    private Axe axe;
    public void setAxe(Axe axe ){
    
    
        this.axe=axe;
    }
    @Override
    public void useAxe(){
    
    
        System.out.println(axe.chop());
    }
}

public class StoneAxe implements Axe{
    
    
    @Override
    public String chop(){
    
    
        return "石斧砍柴好慢";
    }
}

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <!-- 配置名为person的Bean,其实现类是org.crazyit.app.service.Person类 -->
    <bean id="chinese" class="Chinese">
        <!-- 控制调用setAxe()方法,将容器中axe Bean作为传入参数 -->
        <property name="axe" ref="stoneAxe"/>
    </bean>
    <!-- 配置名为axe的Bean,其实现类是org.crazyit.app.service.Axe类 -->
    <bean id="stoneAxe" class="StoneAxe"/>
    <!-- 配置名为win的Bean,其实现类是javax.swing.JFrame类 -->
    <bean id="win" class="javax.swing.JFrame"/>
    <!-- 配置名为date的Bean,其实现类是java.util.Date类 -->
    <bean id="date" class="java.util.Date"/>
</beans>

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanTest {
    
    
    public static void main(String[] args)throws Exception
    {
    
    
        // 创建Spring容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
        // 获取id为person的Bean
        Person p = ctx.getBean("chinese" , Person.class);
        // 调用useAxe()方法
        p.useAxe();
    }
}

Insert picture description here

Three basic points of using Spring IoC container
  • The components of the application program are interface-oriented. Interface-oriented programming can promote the refined relationship between components to the interface level, which is conducive to the later expansion of the project.
  • The components of the application are no longer actively created by the program, but are generated and initialized by the Spring container.
  • Spring uses configuration files or annotations to manage the implementation classes and dependencies of Beans. The Spring container uses reflection to create instances based on configuration files or annotations and injects dependencies into them.

Construction injection

public class Chinese implements Person {
    
    
    private Axe axe;
    public Chinese(Axe axe){
    
    
        this.axe=axe;
    }
    @Override
    public void useAxe(){
    
    
        System.out.println(axe.chop());
    }
}

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <!-- 配置名为person的Bean,其实现类是org.crazyit.app.service.Person类 -->
    <bean id="chinese" class="Chinese">
       <constructor-arg ref="stoneAxe"/>
    </bean>
    <!-- 配置名为axe的Bean,其实现类是org.crazyit.app.service.Axe类 -->
    <bean id="stoneAxe" class="StoneAxe"/>
    <!-- 配置名为win的Bean,其实现类是javax.swing.JFrame类 -->
    <bean id="win" class="javax.swing.JFrame"/>
    <!-- 配置名为date的Bean,其实现类是java.util.Date类 -->
    <bean id="date" class="java.util.Date"/>
</beans>

The difference between the two

The difference is: the timing of creating the Axe property in the Person instance is different. The setting injection is to first create a Bean instance through the parameterless constructor, and then call the corresponding setter method to inject the dependency: while the construction injection directly calls the parameterized constructor After the Bean instance is created, the dependency injection has been completed.

Guess you like

Origin blog.csdn.net/qq_41827511/article/details/105281084