The article is hostedGitHub, you can go to GitHub to read, welcome to Star! Search wechat public code out of Offer to receive a variety of learning materials!
SpringDI (Dependency Injection)
I. Overview of DI
Dependency Injection is a form of Dependency Injection.
Simply put, when Spring creates an object, it assigns values to its properties. This is called dependency injection.
Visually, dependencies between components are determined by the container at run time, i.e. the container dynamically injects a dependency into the component.
What is DI
2.1 Understand the idea of DI
Having looked briefly at DI (dependency injection), we can also split dependency injection in the form of IOC (Inversion of control) while looking at the term dependency injection.
As the name implies, dependency injection is a combination of the words “dependency” and “injection”, so let’s take a look at these two words separately!
2.2 depend on
The word dependence can be broken down into many elements. For example, a dependency condition must be reached by two objects, who depend on whom, and what one depends on from the other. Here we can enumerate the cases according to these conditions:
- In terms of who depends on whom, of course, applications depend on the IOC container. This dependency arises because the application relies on the external resources required by the objects provided by the IOC container. (It can be interpreted as an entrance, though not so strictly!)
2.3 injection
It can be injected once and can be divided into many elements. For example, injection can be broken down into who injected whom and what was injected. Here we can also list these cases according to the two conditions:
- In terms of who is injecting whom, IOC as a container must be the injected object, which means we inject the required objects into the IOC container. As for what was injected, it was obvious that it was objects, resources, data, and so on that we needed for our project. Simply put, we need external resources that can be injected into the IOC container and reversed control of the injected objects by the IOC container!
- IOC’s purpose is to dynamically provide one object with the other objects it needs during the operation of the system. 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 implementation injection, because javabeans generally implement Setter methods, so Setter method injection has become one of our common injection methods.
3.1.1 define javabeans
Define a JavaBean and give it Setter methods
package com.mylifes1110.bean;
import java.util.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
The Lombok@Data annotation provides Setter methods
@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;
}
Copy the code
3.1.2 Injecting various data types
Note: The Date type is processed by Spring. 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> <! <property name="names"> < List > <value>Ziph</value> <value>Join</value> </property> <! < phone "> < Set > <value>110</value> <value>120</value> </ Set > </property> <! Properties type --> <property name="files"> <props> <prop Key ="first">One</prop> <prop Key ="second">Two</prop> <prop key="third">Three</prop> </props> </property> <! Property name=" Countries "> < Map > <entry key="CHINA" value=" CHINA" /> <entry key="USA" value=" United States "/> <entry key="USA" value=" United States "/> <entry Key ="UK" value=" UK" /> </map> </property> </bean>Copy the code
3.1.3 Injecting self-built Type Data
The Service layer needs a Dao layer implementation class object. We can use injection mode to achieve 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>
Copy the code
Inject the created Bean object into another object, such as one JavaBean object, as a property of another JavaBean object
<! - secondary bean, was as properties - > < bean id = "address" class = "com. Mylifes1110. Beans. Address" > < property name = "position" value = "Shanghai" / > <property name="zipCode" value="100001" /> </bean> <! - main beans, the main body of operation - > < bean id = "user" class = "com. Mylifes1110. Beans. User" > <! Property name="address" ref="address" /> </bean>Copy the code
3.2 Constructor injection
When an object is created, the Spring factory assigns values to its properties via constructors. Since some frameworks or projects do not provide setters for Javabeans, we can use their constructors for injection. Don’t tell me, no constructor is provided! (Just kidding!)
3.2.1 define javabeans
Define a JavaBean object and provide a constructor for it
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; }}Copy the code
3.2.2 Constructor injection
<! Injection - structure - > < bean id = "u3" class = "com. Mylifes1110. Beans. Student" > <! <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>Copy the code
3.3 Automatic Injection
You do not specify in the configuration which attribute to assign and what value to assign. Spring automatically looks up a bean in the factory and injects property values into properties based on some “principle”.
3.3.1 Injection Scenario
The Dao layer implementation class object is injected into the Service layer and the method is 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); }}Copy the code
3.3.2 Two modes of automatic injection
Automatically inject values based on the name
<bean id="UserDao" class="com.mylifes1110.dao.impl.UserDaoImpl"/> <! - the attribute name based automatic injection in UserServiceImpl value - > < bean id = "userService" class = "com. Mylifes1110. Service. Impl. UserServiceImpl" autowire="byName"/> </beans>Copy the code
Automatic injection of values based on the type, according to the implementation of the interface to judge and automatic injection of values, if there are too many implementation classes implementing this interface, it will choose the implementation of the same name among many implementation classes implementing this interface for injection. (Now according to judgment, if not successful, according to the name injection)
<bean id="userDao" class="com.mylifes1110.dao.UserDaoImpl" /> <! - for UserServiceImpl properties based on the type of automatic injection value - > < bean id = "userService" class = "com. Mylifes1110. Service. Impl. UserServiceImpl" autowire="byType"/> </beans>Copy the code
3.4 Automatic annotation injection
Note the name | describe |
---|---|
@Autowired | Automatic injection based on type |
@Resource | Automatic injection based on name |
@Qualifier(“userDAO”) | Specifies the ID of the bean to be injected automatically, usually in conjunction with @autowired |
@Value | Inject simple type data (JDK8 basic data types +String) |
Inject the Dao layer into the Service layer using type-based automatic injection
@Service
public class UserServiceImpl implements UserService {
@Autowired // Inject a bean of type UserDao
@Qualifier("userDao") // If there are multiple beans of type UserDao, you can use this annotation to specify one of them
private UserDao userDao;
}
Copy the code
Inject the Dao layer into the Serivce layer using name-based automatic injection
@Service
public class UserServiceImpl implements UserService {
@Resource("userDao") // Inject the bean with id= "userDao"
private UserDao userDao;
}
Copy the code
Use injection simple type data annotations to accomplish simple injection Javabeans
public class User{
@Value("1") // Inject numbers
private Integer id;
@Value("Ziph") / / injection String
private String name;
}
Copy the code