1. 程式人生 > 實用技巧 >Spring學習1_IOC理論推導

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();
       
    }
}