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