首页 > 其他分享 >IOC控制反转

IOC控制反转

时间:2022-11-04 18:24:39浏览次数:56  
标签:控制 UserDao 反转 void class getUser userDao IOC public

IOC控制反转

1.set注入

  1. UserDao

    public interface UserDao {
        void getUser();
    }
    
  2. UserDaoImpl实现类

    public class UserDaoImpl implements UserDao{
        @Override
        public void getUser() {
            System.out.println("调用默认方式获取用户");
        }
    }
    
    public class UserDaoMysqlImpl implements  UserDao{
        @Override
        public void getUser() {
            System.out.println("mysql实现方式");
        }
    }
    
    public class UserDaoOracleImmp implements UserDao{
        @Override
        public void getUser() {
            System.out.println("oracl实现方式");
        }
    }
    
  3. UserService业务层

   public interface UserService {
       void getUser();
   }
  1. UserServiceImpl实现类
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }

    @Override
    public void getUser() {
        userDao.getUser();
    }
}
  1. Test类
public class Test {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        userService.setUserDao(new UserDaoOracleImmp());
        userService.getUser();
    }
}
  • 不用再去管理对象的创建,降低系统耦合性,可以更加专注在业务的实现

标签:控制,UserDao,反转,void,class,getUser,userDao,IOC,public
From: https://www.cnblogs.com/KxWanna/p/16858697.html

相关文章