[Spring Advanced Series丨Part 5] Detailed explanation of dependency injection in Spring

Insert image description here

1. Description

  • full name

    Dependency Injection(DI)

  • Relationship with IoC

IoC and DI actually mean the same thing, you can say:IoC is an idea, DI is a concrete implementation of this idea

  • Dependency management

From now on, it will be maintained by spring. If the current class needs to use objects of other classes, spring will provide them for us. We only need to specify them in the configuration file.

  • Maintenance of dependencies

    ​ Called dependency injection.

  • Data that can be injected: There are three categories

    ​ Basic types and String.

    ​Other bean types (beans configured in the configuration file or annotated)

    ​ Complex type/collection type

  • Injection methods: There are three types

    ​ The first type: use the constructor to provide

    ​Second: Use the set method to provide

    ​The third type: provided using annotations (refer to Chapter 7)

2. Constructor injection

2.1. Method 1 [index index method]

2.1.1. Define Bean

public class Person {
    
    
    
    private Integer id;
    
    private String name;	// 姓名
    
    private Integer age;	// 年龄
  
  	private Double weight;	// 体重

    public Person(Integer id, String name, Integer age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

2.1.2. Configure beans in the main configuration file

<beans>    
	<bean id="person" class="cn.bdqn.Person">
        <constructor-arg index="0" value="1" />
        <constructor-arg index="1" value="王浩"/>
        <constructor-arg index="2" value="20"/>
    </bean>
</beans>

2.1.3. Testing

@Test
public void testPerson() throws Exception{
    
    
    // 1、读取主配置文件信息,获取核心容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

    Person person = (Person) ac.getBean("person");

    System.out.println(person);	// Person{id=1, name='王浩', age=20}
}

2.2. Method 2 [index+type combination method]

Note: Case 1 uses the index index method to achieve injection. As far as the current case is concerned, it is completely fine. However, if the following conditions exist in the Bean, it may not be applicable.

Requirements: I now want to create an object of the Person class and call the Person(Integer id, String name, Double weight) constructor

2.2.1. Define Bean

Description: Initialize the weight attribute in the Person class and add a constructor specifically for it

public class Person {
    
    

    private Integer id;

    private String name;    // 姓名

    private Integer age;    // 年龄

    private Double weight;  // 体重

    public Person(Integer id, String name, Integer age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }

  	// 专门为weight属性定义的构造方法
    public Person(Integer id, String name, Double weight) {
    
    
        this.id = id;
        this.name = name;
        this.weight = weight;
    }
}

2.2.2. Main configuration file configuration Bean

<beans>    
	<bean id="person" class="cn.bdqn.Person">
        <constructor-arg index="0" value="1" />
        <constructor-arg index="1" value="王浩"/>
        <constructor-arg index="2" value="180"/>
    </bean>
</beans>

2.2.3. Testing

@Test
public void testPerson() throws Exception{
    
    
    // 1、读取主配置文件信息,获取核心容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

    Person person = (Person) ac.getBean("person");

    System.out.println(person);	// Person{id=1, name='王浩', age=180}
}

After testing, I found that it did not meet my needs. I was still looking for the public Person(Integer id, String name, Integer age) construction method.

2.2.4. Solution

Explicitly specify the type via type.

<bean>
  	<bean id="person" class="cn.bdqn.Person">
        <constructor-arg index="0" type="java.lang.Integer" value="1" />
        <constructor-arg index="1" type="java.lang.String" value="王浩"/>
        <constructor-arg index="2" type="java.lang.Double" value="180"/>
    </bean>
</bean>

2.3. Method three [name method]

The first two methods can indeed solve the problem through index+type, but I always feel that it is still a bit troublesome. Is there a simpler way? Just use it directlyParameter name formatEasier to read and use.

2.3.1. Define Bean

The definition of Bean is the same as 2.2.1.

2.3.2. Main configuration file configuration Bean

<beans>
	  <bean id="person" class="cn.bdqn.Person">
        <constructor-arg name="id" value="2"/>
        <constructor-arg name="name" value="史周冲"/>
        <constructor-arg name="age" value="3"/>
    </bean>
</beans>

2.3.3. Testing

@Test
public void testPerson() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        Person person = (Person) ac.getBean("person");

        System.out.println(person);	// Person{id=1, name='王浩', age=3}
}

2.4. Additional details

2.4.1. Define Bean

public class Person {
    
    

    private Integer id;

    private String name;    // 姓名
    
    private Date birthday;  // 出生日期

    public Person(Integer id, String name, Date birthday) {
    
    
        this.id = id;
        this.name = name;
        this.birthday = birthday;
    }
}

2.4.2. Main configuration file configuration Bean

<beans>
  	 <bean id="person" class="cn.bdqn.Person">
        <constructor-arg name="id" value="2"/>
        <constructor-arg name="name" value="史周冲"/>
        <constructor-arg name="birthday" value="2019-09-09" />
    </bean>
</beans>

2.4.3. Testing

After testing, I found that the program reported an error. The reason was: it expected a Date type, but now you passed a string, and the data type did not match.

Unsatisfied dependency expressed through constructor parameter 2: Could not convert argument value of type [java.lang.String] to required type [java.util.Date]

2.4.4. Solution

<beans>
  	<bean id="person" class="cn.bdqn.Person">
        <constructor-arg name="id" value="2"/>
        <constructor-arg name="name" value="史周冲"/>
      	<!-- 注意:用了ref属性-->
        <constructor-arg name="birthday" ref="currentDate"/>
    </bean>
	
  	<!-- 定义日期Bean,Spring就会帮助我们new一个Date对象-->
    <bean id="currentDate" class="java.util.Date"/>
</beans>

2.5. Summary

  • Tags used:

    ​ constructor-arg

  • Where the label appears:

    ​The inside of the bean tag

  • Attributes in tags:

    ​ type: used to specify the data type of the data to be injected.

    ​ Index: Used to specify the data to be injected and assign the parameter at the specified index position in the constructor. The index position starts from 0.

    ​ name: used to specify the parameter assignment to the specified name in the constructor.

    ​ value: used to provide basic type and String type data.

    ref: Reference, used to specify other bean type data. It refers to the bean object that appears in spring's Ioc core container.

  • Advantage:

    ​ Suppose we need to explicitly initialize some data when creating an object, then this method is obviously good. Because when creating an object through the constructor, the object cannot be successfully created without specifying specific parameters. Can act as a constraint.

  • Disadvantages:

    ​ Changed the instantiation method of bean objects so that if we do not use these data when creating objects, we must provide them.

3. Set method injection

3.1. Define Bean

public class User {
    
    

    private String name;

    private Date born;

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

    public void setBorn(Date born) {
    
    
        this.born = born;
    }
}

Note: The set injection method does not need to generate a get method

3.2. Main configuration file configuration Bean

<bean id="currentDate" class="java.util.Date"/>
    
<bean id="user" class="cn.bdqn.User">
    <property name="name" value="宋炜烨"/>
    <property name="born" ref="currentDate"/>
</bean>

3.3. Testing

@Test
public void testUser() throws Exception{
    
    
        // 1、读取主配置文件信息,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        User user = (User) ac.getBean("user");

        System.out.println(user);	// User{name='宋炜烨', born=Thu Nov 14 22:29:11 CST 2019}
}

3.4. Summary

  • Tags involved

    ​ property

  • where it appears

    ​The inside of the bean tag

  • Label properties

    ​ name: used to specify the name of the set method called during injection.

    ​ value: used to provide basic type and String type data.

    ref: used to specify other bean type data. It refers to the bean object that appears in spring's Ioc core container.

  • Advantage

    There are no clear restrictions when creating objects, and the default constructor can be used directly.

  • Disadvantages

    ​ If a certain member attribute must have a value, it is possible that the value is not injected through the set method when the object is used again, and a null value may be obtained.

4. Injection of complex types

4.1. Inject array type [array]

4.1.1. Define Bean

public class Cat {
    
    
    
    private String[] arrs;

    public void setArrs(String[] arrs) {
    
    
        this.arrs = arrs;
    }
}

4.1.2. Main configuration file configuration Bean

<beans>
  <bean id="cat" class="cn.bdqn.Cat">
          <property name="arrs">
              <array>
                  <value>崔灿</value>
                  <value>时贝妮</value>
              </array>
          </property>
  </bean>
</beans>

4.2. Inject List type [list]

4.2.1. Define Bean

public class Cat {
    
    

    private List<String> arrList;

    public void setArrList(List<String> arrList) {
    
    
        this.arrList = arrList;
    }
}

4.2.2. Main configuration file configuration Bean

<beans>
	 <bean id="cat" class="cn.bdqn.Cat">
        <property name="arrList">
            <list>
                <value>乔峰</value>
                <value>马夫人</value>
            </list>
        </property>
    </bean>
</beans>

4.3. Inject Set type [set]

4.3.1. Define Bean

public class Cat {
    
    

    private Set<String> arrSet;

    public void setArrSet(Set<String> arrSet) {
    
    
        this.arrSet = arrSet;
    }
}

4.3.2. Main configuration file configuration Bean

<beans>
	    <bean id="cat" class="cn.bdqn.Cat">
            <property name="arrSet">
                <set>
                    <value>段誉</value>
                    <value>鸠摩智</value>
                </set>
            </property>
   	 	</bean>
</beans>

4.4. Inject Map type [Map]

4.4.1. Define Bean

public class Cat {
    
    

    private Map<String,Object> arrMap;

    public void setArrMap(Map<String, Object> arrMap) {
    
    
        this.arrMap = arrMap;
    }
}

4.4.2. Main configuration file configuration Bean

<bean>
	<property name="arrMap">
        <map>
           	<entry key="S001" value="彭依凝"/>
            <entry key="S002" value="段康家"/>
            <entry key="S003" value="王浩"/>
        </map>
    </property>
</bean>

4.5. Inject Properties type

4.5.1. Define Bean

public class Cat {
    
    

    private Properties props;

    public void setProps(Properties props) {
    
    
        this.props = props;
    }
}

4.5.2. Main configuration file configuration Bean

<bean id="cat" class="cn.bdqn.Cat">
     <property name="props">
            <props>
                <prop key="A001">虚竹</prop>
                <prop key="A002">扫地僧</prop>
            </props>
     </property>
</bean>

4.6. Summary

  • Tags used to inject into the List structure collection:

    ​ list、array、set

  • Tags used for Map structure collection injection:

    ​ map 、props

  • Summarize

    The structure is the same and the labels are interchangeable

Recommended books

Insert image description here
"The Definitive Guide to Spring Batch"Main content:

  • Explore what's new in Spring Batch 4.

  • Use the Spring Batch project to complete limited batch processing tasks in a cloud environment.

  • Understand the latest Java and Spring Boot based configuration technologies through some examples

  • Master batch processing in complex scenarios and cloud environments

  • Develop batch applications that run on modern platforms

  • In addition to Spring Batch, use other parts of the Spring Portfolio to develop mission-critical batch applications

Book purchase link:Click here to enter

book delivery event

How to participate:Click to enter and participate. It is fair, just and open. The fewer people, the better to win!


Insert image description here

Guess you like

Origin blog.csdn.net/m0_63947499/article/details/134577569