[SSM-Spring Chapter 02] IOC Container-Inversion of Control and Dependency Injection

Inversion of Control (IOC) and Dependency Injection (DI)

Inversion of control (Inversion of Control, the IoC ) is a relatively abstract concept, the core is the Spring framework, a computer program for subtractive coupling problem .
Dependency injection (the Dependency Injection, the DI ) of IoC is another way of saying, but from a different perspective, the same concept is described.

Inversion of control is a way to generate or obtain specific objects through description (in Spring, it can be XML or annotation ) and through a third party. It is the IoC container that implements the inversion of control in Spring, and its implementation method is dependency injection.
Dependency injection is a member variable that the Spring container assigns the dependent object to the caller, which is equivalent to injecting the instance it depends on for the caller

Spring IOC container

  The design of Spring IoC container is mainly based on two interfaces of BeanFactory and ApplicationContext .

1. BeanFactory

创建BeanFactory实例时,需要提供XML文件的**绝对路径。**
//创建BeanFactory 实例 -- 绝对路径
BeanFactory beanFactory = new XmlBeanFactory(
			new FileSystemResource("E:\\SSM\\Spring\\src\\com\\xgf\\ioc\\applicationContext.xml")

2. ApplicationContext

2.1 Created by ClassPathXmlApplicationContext

  ClassPathXmlApplicationContext will find the specified XML configuration file from the classPath directory (src root directory)

//类路径
ApplicationContext context = 
	new ClassPathXmlApplicationContext("com/xgf/ioc/applicationContext.xml");

2.2 Created by FileSystemXmlApplicationContext

  FileSystemXmlApplicationContext will find the XML configuration file from the absolute path of the specified file , find and load it to complete the instantiation of ApplicationContext

// 绝对路径 
ApplicationContext appCon = 
	new FileSystemXmlApplicationContext("E:\\SSM\\Spring\\src\\com\\xgf\\ioc\\applicationContext.xml");
TestDao tt = (TestDao)appCon.getBean("test");

2.3 Instantiate the ApplicationContext container through the web server

When the Web server instantiates the ApplicationContext container, it generally uses an implementation based on org.springframework.web.context.ContextLoaderListener .
This method requires the following code to be added to web.xml:

<context-param>
  	<!-- 加载src目录下的applicationContext.xml文件 -->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>
  		classpath:applicationContext.xml
  	</param-value>
  </context-param>
  <!-- 指定以ContextLoaderListener方式启动Spring容器 -->
  <listener>
  	<listener-class>
  		org.springframework.web.context.ContextLoaderListener
  	</listener-class>
  </listener>

DI dependency injection type

  Spring IoC container implemented method is dependent injection, dependency injection effect in the Spring Framework is to create objects , dynamically its dependent objects (e.g., attribute value) Bean injection assembly .

Dependency injection of the Spring framework usually has two implementation methods:

One is construction method injection, and the other is property setter method injection.

1. Constructor injection

  The Spring Framework is the Java reflection mechanism , dependency injection is completed by the constructor

2. Property setter method injection

  Setter method injection is the most mainstream injection method in the Spring framework . It uses the setter method defined by the Java Bean specification to complete the injection, which is flexible and highly readable. Setter method injection, the Spring framework is also implemented using Java's reflection mechanism.

Steps:
1. Create the bean class
2. Create the Controller class to host the Controller to spring and let spring create its objects
3. Create service interface implementation class serviceImpl to host serviceImpl to spring, let spring create its object
4. Create Dao interface implementation class DaoImpl to host DaoImpl to spring, let spring create its object
5. Test setter method injection in Test

3. Case implementation of setter method injection to simulate IOC container injection (Create ApplicationContext by ClassPathXmlApplicationContext)

Steps:
1. Create the bean class
2. Create the Controller class to host the Controller to spring and let spring create its objects
3. Create service interface implementation class serviceImpl to host serviceImpl to spring, let spring create its object
4. Create Dao interface implementation class DaoImpl to host DaoImpl to spring, let spring create its object
5. Test setter method injection in Test

Introduce spring's dependency in pom.xml

<!--spring 核心容器-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

  1. Create User class (Spring/src/main/java/com/xgf/ioc/bean/User.java)
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class User {
    
    
    private String name;
    
    public User() {
    
    
        System.out.println("调用User的无参构造器");
    }
    public User(String name) {
    
    
        System.out.println("调用User的name参数构造器");
        this.name = name;
    }
    
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    
    @Override
    public String toString() {
    
    
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

  1. Create the ApplicationContext.xml configuration file under resources
    (Spring/src/main/resources/com/xgf/ioc/applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress SpringFacetInspection -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--  配置注解扫描  扫描com.xgf.ioc下的所有文件 -->
    <context:component-scan base-package="com.xgf.ioc"/>
</beans>
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20200919160104455.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNTQyNTM0,size_16,color_FFFFFF,t_70#pic_center)


3. 创建测试类(Spring/src/main/java/com/xgf/ioc/Test/TestIOC.java)

```java
/*
* 测试IOC依赖注入 - 通过setter方法注入
* */
public class TestIOC {
    public static void main(String[] args) {
        //注解进行配置,实例化ApplicationContext容器  通过ClassPathXmlApplicationContext方式实例化ApplicationContext
        ApplicationContext context = new ClassPathXmlApplicationContext("com/xgf/ioc/applicationContext.xml");

        //通过getBean方法从ApplicationContext容器当中获取User对象
        UserController userContrller = (UserController)context.getBean("userController");

        //调用User的name参数构造器测试
        userContrller.saveUser(new User("GF_浪夏一学"));

    }
}
  1. 创建Controller(Spring/src/main/java/com/xgf/ioc/controller/UserController.java)
/*
    @Controller注解  该注解用于标注一个控制器组件类
    容器一启动就会实例化  创建好之后以类名首字母小写放到容器中
    UserController 启动容器之后  创建好之后 变成---> key= userController value=new UserController();
* */
@Controller
public class UserController {
    
    
    /*
    @Autowired注解 按照类型进行匹配  - 自动装载
    该注解可以对类成员变量、方法及构造方法进行标注,完成自动装配的工作。
    通过 @Autowired的使用来消除setter 和getter方法。默认按照Bean的类型进行装配。
    */
    @Autowired
    private UserService userService;//  香当于执行了实例化  private UserService userService = new UserServiceImpl();

    //调用service的方法saveUser
    public void saveUser(User user){
    
    
        userService.saveUser(user);
    }
}
  1. 创建Service(Spring/src/main/java/com/xgf/ioc/service/UserService.java)
public interface UserService {
    
    
    void saveUser(User user);
}
/*
    @Service
	该注解用于标注一个业务逻辑组件类(Service层),其功能与@Component()相同。
    value是默认bean的id
    容器加载后会实例化,创建UserService对象
*/
@Service(value="userService")
public class UserServiceImpl implements UserService{
    
    
    @Autowired
    private UserDao userDao;

    @Override
    public void saveUser(User user) {
    
    
        userDao.saveUser(user);
    }
}
  1. 创建 dao (Spring / src / main / java / com / xgf / ioc / dao / UserDao.java)
public interface UserDao {
    
    
    void saveUser(User user);
}
/*
@Repository
	该注解用于将数据访问层(DAO)的类标识为Bean,即注解数据访问层Bean,其功能与@Component()相同。
	容器加载就会被实例化
*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    
    

    @Override
    public void saveUser(User user) {
    
    
        System.out.println("调用dao层userDao的saveUser方法,保存用户:"+user.getName());
    }
}
  1. Run result (achieve successful injection)

Insert picture description here
By creating the User object, calling the Controller, the service is automatically loaded through spring's @Autowired annotation, and then the dao is automatically loaded in the service, and finally the injection is realized.

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108679399