Spring 6 [Two ways of DI, automatic injection] (4) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Eight, two ways of DI

Nine, automatic injection


Eight, two ways of DI

IoC is a process in which the IoC container helps instantiate beans and injects associated attributes (objects) inside the IoC container. The above demonstrates how to instantiate the Bean, and the following demonstrates how to inject properties into the Bean. That is to say, it is explaining the other half of the function of IoC/DI.

When explaining DI earlier, the official document clearly stated that there are two ways of DI. The official website description is as follows:

Translated, it is the effect of the following picture:

 

1. Construct injection 

Construction injection requires that a parameterized construction method must be provided in the bean (it is best to provide no parameters, this position is not used. But if other positions are not injected through construction, the default is to call no parameter construction.

1.1 Check whether there is a parameterized construction method in the Bean class

Check whether com.bjsxt.pojo.People has a parameterized construction method, and pay attention to the type and order of the parameter list of the construction method.

public class People {
      private int id;
      private String name;
      // 无参数构造
   public People() {}
   // 有参构造
   public People(int id, String name) {
     this.id = id;
     this.name = name;
   }
// getter/setter 没有粘贴到文档中
}

1.2 Configure beans

In the configuration file applicationContext.xml, the value of a parameter in the construction method can be set through the sub-tag.

 explain:

There are 5 attributes in constructor-arg, which are divided into 2 categories.

(1) Used to determine which attribute to assign

name: parameter name

index: parameter index. Counting starts from 0.

type: parameter type. 8 basic data types can directly write keywords. Other types require the fully qualified path to the write type. If you only need to use one of these three attributes, you can tell Spring exactly which constructor parameter to set can be used. If you can't be precise to a certain constructor parameter, you can use multiple together.

(2) Set the value of the attribute

value: Simple data type is set directly. Spring does the type conversion automatically.

ref: Need to refer to the id of another bean. That is to say, this parameter is a class type, and the object of this class is also managed by the Spring container.

 The following code uses type to confirm which parameter is assigned to the constructor. You can also try to use other properties to confirm the parameters.

<bean id="peo4" class="com.tong.pojo.People">
    <constructor-arg type="int" value="1"></constructor-arg>
    <constructor-arg type="java.lang.String" value="张三"></constructor-arg>
</bean>

1.3 Write a test class and observe the console running results

/*
DI构造注入
*/
@Test
void constructorDI(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    People peo4 = context.getBean("peo4", People.class);
    System.out.println(peo4);
}

The console output contains the configured value

2. Set value injection (setter injection) 

2.1 Check whether there is a Setter method in the Bean class

Setter injection is generally used in conjunction with a parameterless construction method. So there is a parameterless constructor in the class.

package com.tong.pojo;
public class People {
     private int id;
     private String name;
     public People() {}
     public People(int id, String name) {
           this.id = id;
           this.name = name;
       }

     public int getId() {
            return id;
      }
     public void setId(int id) {
            this.id = id;
      }
     public String getName() {
            return name;
      }
     public void setName(String name) {
           this.name = name;
      }
    @Override
    public String toString() {
            return "People{" + "id=" + id + ", name='" + name + '\'' + '}';
       }
}

1.2 Configuring Beans

Reconfigured a bean tag and set id="peo5".

Call the setter method of the class through the label.

1. name: attribute name.

2. value: attribute value.

3. ref: Refers to the id attribute of another bean tag.

<bean id="peo5" class="com.tong.pojo.People">
   <property name="id" value="2"></property>
   <property name="name" value="李四"></property>
</bean>

1.3 Write a test class and observe the console results

Obtain the peo5 bean in the test class and output it to the console to check whether it contains the set value.

3. Mixed use of construction injection and set value injection

It is also possible to mix constructor injection and setter injection. As long as there are corresponding construction methods and setter methods in these two methods, you can use one of them to set the value of some properties.

First ensure that there is a parameterized construction method in People, and it contains a setter method for the name attribute.

package com.tong.pojo;
public class People {
     private int id;
     private String name;
     public People() {}
    // 只有id属性的构造方法
     public People(int id) {
            this.id = id;
      }
     public People(int id, String name) {
            this.id = id;
            this.name = name;
       }
     // getter/setter 没有粘贴到文档中
     public int getId() {
            return id;
       }
     public void setId(int id) {
            this.id = id;
       }
     public String getName() {
           return name;
      }
     public void setName(String name) {
          this.name = name;
      }
    @Override
    public String toString() {
           return "People{" + "id=" + id + ", name='" + name + '\'' + '}';
   }
}

Mix both ways in configuration file

<bean id="peo6" class="com.tong.pojo.People">
    <constructor-arg index="0" value="3"></constructor-arg>
    <property name="name" value="王五"></property>
</bean>

Obtain the peo5 bean in the test class and output it to the console to check whether it contains the set value.

4. The corresponding writing method of different attribute types

When explaining the two implementations of DI earlier, the attributes are all simple data types. If the attribute of the class is an array, collection, object, etc., it needs to be set in the following way. These tags are all subtags of or .

Once the following sub-tag method is used, the value attribute or ref attribute cannot be set or set. And it is necessary to provide the corresponding name and attribute of the corresponding type in the People class. In the following example, the code for the corresponding type and name attribute provided by the People class is not pasted.

4.1 Referencing other beans

If you need to refer to other beans, you can directly use the ref reference in the property tag. It is also possible to use the sub-tag ref, but it is not as simple as using the ref attribute directly.

<bean id="tea" class="com.tong.pojo.Teacher"></bean>
    <bean id="peo7" class="com.tong.pojo.People">
    <property name="teacher" ref="tea"></property>
</bean>

4.2 Set type

<bean id="peo7" class="com.tong.pojo.People">
    <property name="hover">
     <set>
       <value>童小纯</value>
       <value>听smallming</value>
    </set>
   </property>
</bean>

4.3 List type

<bean id="peo7" class="com.tong.pojo.People">
   <property name="subjects">
    <list>
      <value>java</value>
      <value>前端</value>
   </list>
  </property>
</bean>

4.4 Array type

<bean id="peo7" class="com.tong.pojo.People">
   <property name="teachers">
     <array>
       <value>小童</value>
       <value>张佳明</value>
     </array>
   </property>
</bean>

4.5 Map type

<bean id="peo7" class="com.tong.pojo.People">
   <property name="phone">
    <map>
      <entry key="姓名" value="18612345678"></entry>
    </map>
  </property>
</bean>

4.6 Prop value type

Prop is the Properties type. Properties is a subtype of HashTable. The content satisfies the Key-value.

<bean id="peo7" class="com.tong.pojo.People">
   <property name="properties">
     <props>
        <prop key="a">a1</prop>
        <prop key="b">b1</prop>
     </props>
   </property>
</bean>

4.7 Null value types

<bean id="peo7" class="com.tong.pojo.People">
    <property name="phone">
      <null></null>
    </property>
</bean>

Nine, automatic injection

In Spring, automatic injection of beans is allowed. There are two ways to configure.

1. Configure the default-autowire attribute in the root tag. Strategies for auto-injection throughout Spring. There are 5 possible values.

2. default: default value. Not automatically injected.

3. no: no automatic injection.

4. byName: Automatic injection by name. It will automatically find the bean with the same name as the current property in the container for injection.

5. byType: Automatic injection by type. It will automatically find beans that match the current bean type in the container for injection. An exception will occur if multiple beans of the same type are injected.

6. constructor: inject through the construction method. Look for a parameter in the bean's constructor that contains other bean types. If it is automatically injected into it. The type is first byType and then byName. If it is not found, it will not be injected. Note: The constructor type is the same as other Bean types.

<?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"
default-autowire="byName">
<bean id="peo" class="com.tong.pojo.People" ></bean>
</beans>

Configure the autowire attribute in the tag. Same value as default-autowire. The only thing to note is that default represents the value of the global default-autowire. If both autowire and default-autowire exist, autowire takes effect.

<bean id="peo" class="com.tong.pojo.People" autowire="byType"></bean>

Tips: Automatic injection refers to automatic injection between beans. To be able to automatically inject, you must ensure that the Spring container contains beans that can be automatically injected

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131796891