Spring01:概述及IOC理論推導

植樹chen發表於2020-11-27

官網 : http://spring.io/

官方下載地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/

GitHub : https://github.com/spring-projects

Spring01:概述及IOC理論推導

Spring是一個輕量級的控制反轉(IoC)和麵向切面(AOP)的容器(框架)

IOC基礎

新建專案

image-20201126145821948

User

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserDao

public interface UserDao {
    public void getUser();
}

UserdaoImpl

public class UserDaoImpl implements UserDao{

    @Override
    public void getUser() {
        System.out.println("獲取使用者資料");
    }
}

UserService

public interface UserService {
    public void getUser();
}

UserServiceImpl

public class UserServiceImpl implements UserService{
    private UserDao userDao=new UserDaoImpl();

    @Override
    public void getUser(){
        userDao.getUser();
    }
}

測試

public class MyTest {

    @Test
    public void testGetUser(){
        UserServiceImpl service = new UserServiceImpl();
        service.getUser();
    }
}

image-20201126150058043

擴充套件功能

新增實現類UserDaoMySqlImpl

public class UserDaoMySqlImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("MySQL獲取使用者資料");
    }
}

UserServiceImpl中

public class UserServiceImpl implements UserService{

    private UserDao userDao=new UserDaoMySqlImpl();
    @Override
    public void getUser(){
        userDao.getUser();
    }
}

再新增一個UserDaoOracleImpl

public class UserDaoOracleImpl implements UserDao {
    @Override
    public void getUser() {
        System.out.println("Oracle獲取使用者資料");
    }
}

修改UserServiceImpl

public class UserServiceImpl implements UserService{

    private UserDao userDao=new UserDaoOracleImpl();
    @Override
    public void getUser(){
        userDao.getUser();
    }
}

問題:每一次都要修改

解決:使用set()方法實現

public class UserServiceImpl implements UserService{

    private UserDao userDao;
    
    //set實現
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
    
    @Override
    public void getUser(){
        userDao.getUser();
    }
}

測試

@Test
public void testGetUser() {
    UserServiceImpl service = new UserServiceImpl();
    service.setUserDao(new UserDaoMySqlImpl());

    service.getUser();

    //使用Oracle實現
    service.setUserDao(new UserDaoOracleImpl());
    service.getUser();
}

image-20201126151644067

由呼叫者自行建立物件

相關文章