Detailed explanation of SpringDI's four dependency injection methods


LOGO
The article has been hosted on GitHub . You can check it out on GitHub. Welcome bosses to Star!
Search and follow the WeChat public account [Code out Offer] to receive various learning materials!

SpringDI (dependency injection)


1. DI overview

Dependency Injection is Dependency Injection, or DI for short .

To put it simply, when Spring creates an object, assigning values ​​to its properties is called dependency injection.

Visually speaking, the dependency between components is determined by the container at runtime, that is, the container dynamically injects a certain dependency into the component.

2. What is DI

2.1 Understand the idea of ​​DI

A brief understanding of DI (dependency injection), looking at the term dependency injection, we can also split dependency injection in the form of IOC (inversion of control).

As the name implies, dependency injection is a combination of the two words "dependency" and "injection", so let's follow the vine and analyze these two words separately!

2.2 Dependence

The word dependency can be broken down into many elements. For example, to achieve the dependency condition must be two objects , who depends on whom , and one object depends on the other . Here we can enumerate these situations according to these conditions:

  1. Regarding who depends on whom, of course the application depends on the IOC container. Because the application depends on the external resources required by the objects provided by the IOC container, this dependency is generated. (It can be understood as an entrance, although it is not so rigorous!)

2.3 Injection

Once injected, it can be divided into many elements. For example, injection can be decomposed into who injected who and what was injected . Here we can also enumerate these situations based on these two conditions:

  1. Regarding who injects whom, the IOC as a container must be the object to be injected, which means that we inject the objects we need into the IOC container. As for what is injected, it is obvious that it is the objects, resources, data, and so on that our project needs. Simply put, we need external resources to be injected into the IOC container, and the IOC container can realize the inversion of control of the injected object!
  2. IOC is to dynamically provide an object with other objects it needs while the system is running. This is achieved through DI (Dependency Injection).

Three, injection method

3.1 Setter method injection

Setter method injection, it only needs to provide the corresponding Setter method interface to achieve injection. Since JavaBean generally implements the Setter method, Setter method injection has become one of our commonly used injection methods.

3.1.1 Define JavaBean

Define a JavaBean and give it a Setter method

package com.mylifes1110.bean;

import java.util.*;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

//Lombok@Data注解提供了Setter方法
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    private Integer             id;
    private String              password;
    private String              sex;
    private Integer             age;
    private Date                bornDate;
    private String[]            hobbys;
    private Set<String>         phones;
    private List<String>        names;
    private Map<String, String> countries;
    private Properties          files;
}
3.1.2 Inject various data types

Note: The bottom layer of Spring processes the Date type, and the default processing format is "yyyy/MM/dd"

<bean id="User" class="com.mylifes1110.bean.User">
    <!--注入基本数据类型-->
    <property name="id" value="1"/>
    <property name="password" value="123456"/>
    <property name="sex" value="male"/>
    <property name="age" value="18"/>
    <!--注入日期类型-->
    <property name="bornDate" value="1999/09/09"/>
    <!--注入数组类型-->
    <property name="hobbys">
        <array>
            <value>Run</value>
            <value>Jump</value>
            <value>Climb</value>
        </array>
    </property>
    <!--注入List集合类型-->
    <property name="names">
        <list>
            <value>Ziph</value>
            <value>Join</value>
            <value>Marry</value>
        </list>
    </property>
    <!--注入Set集合类型-->
    <property name="phones">
        <set>
            <value>110</value>
            <value>119</value>
            <value>120</value>
        </set>
    </property>
    <!--注入Properties类型-->
    <property name="files">
        <props>
            <prop key="first">One</prop>
            <prop key="second">Two</prop>
            <prop key="third">Three</prop>
        </props>
    </property>
    <!--注入Map集合类型-->
    <property name="countries">
        <map>
            <entry key="CHINA" value="中国"/>
            <entry key="USA" value="美国"/>
            <entry key="UK" value="英国"/>
        </map>
    </property>
</bean>
3.1.3 Inject self-built type data

The Service layer needs a Dao layer to implement class objects, we can use injection to realize the object association between the Service layer and the Dao layer

<bean id="UserDao" class="com.mylifes1110.dao.impl.UserDaoImpl"/>
<bean id="UserService" class="com.mylifes1110.service.impl.UserServiceImpl">
    <property name="userDao" ref="UserDao"/>
</bean>

Inject the created Bean object into another object, such as a JavaBean object as an attribute of another JavaBean object

<!--次要bean,被作为属性-->
<bean id="address" class="com.mylifes1110.bean.Address">
    <property name="position" value="上海市" />
    <property name="zipCode" value="100001" />
</bean>

<!--主要bean,操作的主体-->
<bean id="user" class="com.mylifes1110.bean.User">
    <!--address属性引用address对象-->
    <property name="address" ref="address" />
</bean>

3.2 Construction method injection

When creating an object, the Spring factory assigns values ​​to the properties of the object through the construction method. Since some frameworks or projects do not provide a Setter method for JavaBean, we can use its construction method to inject. Don't tell me, no construction method is provided! (just kidding!)

3.2.1 Define JavaBean

Define a JavaBean object and provide its construction method

public class Student {
    
    
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
  
    //Constructors
  	public Student(Integer id , String name , String sex , Integer age){
    
    
      	this.id = id;
    	this.name = name;
  	    this.sex = sex;
	    this.age = age;
    }
}
3.2.2 Construction method injection
 <!--构造注入-->
<bean id="u3" class="com.mylifes1110.bean.Student">
    <!-- 除标签名称有变化,其他均和Set注入一致 -->
    <constructor-arg name="id" value="1234" /> 
    <constructor-arg name="name" value="tom" />
    <constructor-arg name="age" value="20" />
    <constructor-arg name="sex" value="male" />
</bean>

3.3 Automatic injection

There is no need to specify which attribute to assign to and what value to assign in the configuration. Spring automatically finds a bean in the factory according to a certain "principle" and injects attribute values ​​into the attributes.

3.3.1 Injection scenario

Inject Dao layer implementation class objects into Service layer and call methods to be tested

package com.mylifes1110.service.impl;

import com.mylifes1110.bean.User;
import com.mylifes1110.dao.UserDao;
import com.mylifes1110.service.UserService;

public class UserServiceImpl implements UserService {
    
    
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }

    @Override
    public int insertUser(User user) {
    
    
        System.out.println("------insertUser and UserService------");
        return userDao.insertUser(null);
    }
}
3.3.2 Two ways of automatic injection

Automatically inject values ​​based on names

<bean id="UserDao" class="com.mylifes1110.dao.impl.UserDaoImpl"/>
	<!--为UserServiceImpl中的属性基于名称自动注入值-->
	<bean id="userService" class="com.mylifes1110.service.impl.userServiceImpl" autowire="byName"/>
</beans>

Automatically inject values ​​based on the type, judge and automatically inject values ​​based on the implemented interface. If there are too many implementation classes that implement this interface, it will choose implementation classes with the same name among many implementation classes that implement this interface for injection. (Now according to the judgment, if it is unsuccessful, inject according to the name)

<bean id="userDao" class="com.mylifes1110.dao.UserDaoImpl" />
	<!--为UserServiceImpl中的属性基于类型自动注入值-->
	<bean id="userService" class="com.mylifes1110.service.impl.UserServiceImpl" autowire="byType"/>
</beans>

3.4 Automatic annotation injection

Annotation name description
@Autowired Automatic injection based on type
@Resource Automatic injection based on name
@Qualifier(“userDAO”) Limit the id of the bean to be automatically injected, generally used in conjunction with @Autowired
@Value Inject simple type data (jdk8 basic data types + String type)

Use type-based automatic injection to inject the Dao layer into the Service layer

@Service
public class UserServiceImpl implements UserService {
    
       
    @Autowired //注入类型为UserDao的bean
    @Qualifier("userDao") //如果有多个类型为UserDao的bean,可以用此注解从中指定一个
    private UserDao userDao;
}

Use name-based automatic injection to inject the Dao layer into the Serivce layer

@Service
public class UserServiceImpl implements UserService {
    
       
    @Resource("userDao") //注入id=“userDao”的bean
    private UserDao userDao;
}

Use the injection simple type data annotation to complete the simple injection of JavaBean

public class User{
    
    
    @Value("1")    //注入数字
    private Integer id;
    @Value("Ziph") //注入String
	private String name;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44170221/article/details/107433952