IOC控制反转
1.set注入
-
UserDao
public interface UserDao { void getUser(); }
-
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实现方式"); } }
-
UserService业务层
public interface UserService {
void getUser();
}
- UserServiceImpl实现类
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
- Test类
public class Test {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoOracleImmp());
userService.getUser();
}
}
- 不用再去管理对象的创建,降低系统耦合性,可以更加专注在业务的实现