Spring-Inversion of Control and Dependency Injection

1. Inversion of Control (IOC Inverse of Control)

Let's first understand the concept of control

控制:指的是对成员变量赋值的控制权
控制反转:把对于成员变量赋值的控制权,从代码中反转(转移)到Spring工厂和配置文件中完成
好处:可以解耦合
底层原理:工厂设计模式
  • When we haven't learned Spring, we are directly in the code to complete the assignment of member variables
  • This also shows that control over assignment to member variables is given to the code
  • In this way, the coupling
public class UserServiceImpl implements UserService {
    
    
     private UserDao userDao=new UserDAOImpl();
     
    @Override
    public void register(User user) {
    
    
        userDao.save(user);
    }

    @Override
    public void login(String name, String password) {
    
    
        userDao.queryUserByNameAndPassword(name ,password);
    }
}

But after we learn Spring, we can assign values ​​to member variables through configuration files and Spring factories

  • At this time, the control of member variable assignment is handed over to the Spring configuration file and the Spring factory
  • The advantage of this is that it can be decoupled
  • At this time, control is transferred from the code to the Spring configuration file and Spring factory
public class UserServiceImpl implements UserService {
    
    
   
    private UserDao userDao;

    @Override
    public void register(User user) {
    
    
        userDao.save(user);
    }

    @Override
    public void login(String name, String password) {
    
    
        userDao.queryUserByNameAndPassword(name ,password);
    }
}
 <bean id="userdao" class="com.zyh.basic.UserDAOImpl"></bean>
    <bean id="userservice" class="com.zyh.basic.UserServiceImpl">
        <property name="userDao" >
            <ref bean="userdao"></ref>
        </property>
    </bean>

Inversion of control actually means that the control of member variable assignment is transferred from the code to the Spring configuration file and Spring factory

Spring manages the instantiation and initialization of all Java objects through the IOC container, and controls the dependencies between objects. We call the Java objects managed by the IOC container container Spring Bean, which is no different from creating objects with new

2. Dependency Injection (DI for short)

Dependency Injection is a way of programming in Spring

  • Injection: Assign values ​​to member variables of objects (beans, components) through Spring's factories and configuration files
  • Dependency: Class A needs to use class B, which means that A depends on B. Once there is a dependency, we can define class B as a member variable of A, and finally inject (assign) through Spring's configuration file.
  • Dependency injection can decouple
    insert image description here

Guess you like

Origin blog.csdn.net/qq_52797170/article/details/124222862