ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring学习1_IOC理论推导

2020-07-30 21:31:29  阅读:25  来源: 互联网

标签:UserDaoImpl UserServiceImpl UserDao 推导 Spring void getUser IOC public


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

标签:UserDaoImpl,UserServiceImpl,UserDao,推导,Spring,void,getUser,IOC,public
来源: https://www.cnblogs.com/abc991314/p/13406434.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有