The concept of dependency injection

  • DI stands for Dependency Injection (DI). It has the same meaning as inversion of control (IoC), except that the two terms describe the same concept from both sides.
  • IOC: With the Spring framework, instances of objects are no longer created by the caller. Instead, they are created by the Spring container, which controls the relationship between programs rather than directly by the caller’s program code. In this way, control is transferred from the application code to the Spring container, and control is reversed, which is called inversion of control.
  • DI: From the perspective of the Spring container, the Spring container is responsible for assigning a dependent object to the caller’s member variable. This is equivalent to injecting an instance of its dependency into the caller. This is called Spring dependency injection.

Case study:



UserService.java

package com.xdr.ioc;

public interface UserService {
	public void say();
}
Copy the code

UserServiceImpl.java

package com.xdr.ioc; Public class UserServiceImpl implements UserService{private UserDao UserDao; Public void setUserDao(UserDao UserDao) {this. UserDao = UserDao; } @override public void say() {TODO auto-generated method stub; And execute the output statement this.userdao.say (); System.out.println("userService say hello world!" ); }}Copy the code

applicationContext.xml

<? The 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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <! <bean id="userDao" class="com.xdr.ioc.UserDaoImpl"></bean> <! - add an id for userService instance - > < bean id = "userService" class = "com. XDR. Ioc. UserServiceImpl" > <! <property name="userDao" ref="userDao"></property> </ Bean ></ beans>Copy the code

Test class: testdi.java

package com.xdr.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestDI { public static void main(String[] args) { //1. Initialize the Spring container, Loading the configuration file ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext (" the applicationcontext.xml "); / / 2. Through the container for instance UserService UserService UserService = (UserService) applicationContext. GetBean (" UserService "); //3. Call the say() method userservice.say (); }}Copy the code

Results: