Spring学习1_IOC理论推导

Spring学习1_IOC理论推导

原来的业务实现:

  1. 创建UserDao接口
  2. 创建UserDaoImpl接口的实现类
  3. 创建UserService业务接口
  4. 创建UserServiceImpl业务实现类
  5. 创建测试类

UserDao接口:

public interface UserDao{
    void getUser();
}

UserDaoImpl实现类:

public class UserDaoImpl implements UserDao{
   public void getUser(){
       System.out.println("从数据库获取数据");
   }
}

UserService接口:

public interface UserService{
    void getUser();
}

UserServiceImpl实现类:

public class UserServiceImpl implements UserService{
   private UserDao userDao = new UserDaoImpl(); 
    
   public void getUser(){
       userDao.getUser();
   }
}

MyTest测试类:

public class MyTest(){
    
    public static void main(String[] args){
        UserService userService = new UserServiceImpl();
        
        userService.getUser();
       
    }
}

控制反转实现:

  1. 创建UserDao接口
  2. 创建UserDaoImpl接口的实现类
  3. 创建UserDaoMysqlImpl接口的实现类
  4. 创建UserService业务接口
  5. 创建UserServiceImpl业务实现类
  6. 创建测试类

UserDao接口:

public interface UserDao{
    void getUser();
}

UserDaoImpl实现类:

public class UserDaoImpl implements UserDao{
   public void getUser(){
       System.out.println("从数据库获取数据");
   }
}

UserDaoImpl实现类:

public class UserDaoMysqlImpl implements UserDao{
   public void getUser(){
       System.out.println("从Mysql数据库获取数据");
   }
}

UserService接口:

public interface UserService{
    void getUser();
}

UserServiceImpl实现类:

public class UserServiceImpl implements UserService{
   private UserDao userDao = new UserDaoImpl(); 
    
   public void setUserDao(UserDao userDao){
       this.userDao = userDao;
   }
    
   public void getUser(){
       userDao.getUser();
   }
}

MyTest测试类:

public class MyTest(){
    
    public static void main(String[] args){
        UserServiceImpl userServiceImpl = new UserServiceImpl();
        //这一步就是ioc的核心,由原先的程序new 创建转变为由用户自己创建
        userService.setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
       
    }
}
上一篇:SpringBoot集成MyBatis底层原理及简易实现


下一篇:IDEA的spring入门程序