Spring學習1_IOC理論推導
阿新 • • 發佈:2020-07-30
Spring學習1_IOC理論推導
原來的業務實現:
- 建立UserDao介面
- 建立UserDaoImpl介面的實現類
- 建立UserService業務介面
- 建立UserServiceImpl業務實現類
- 建立測試類
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(); } }
控制反轉實現:
- 建立UserDao介面
- 建立UserDaoImpl介面的實現類
- 建立UserDaoMysqlImpl介面的實現類
- 建立UserService業務介面
- 建立UserServiceImpl業務實現類
- 建立測試類
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();
}
}