spring을 이용한 의존성 주입

이정연·2023년 1월 30일
0

기본지식

목록 보기
4/10
  • 클래스 끼리는 사용하고자 하는 클래스의 객체를 생성해서 참조하게 되면 의존 관계가 성립하게 된다.
  • DI(Dependency Injection)는 IoC 개념을 조금 구체화 시킨 것으로 객체 간의 관계를 느슨하게 해준다.
  • new 키워드를 사용하여 객체를 생성할 때, 클래스 간에 강하게 결합(Tight Coupling)되어 있다고 한다.
  • 인터페이스를 이용하면 느슨한 의존관계를 만들 수 있다.
  • Spring에서는 애플리케이션 코드에서 이루어지는 의존성 주입(DI)을 Spring에서 대신 해준다.

CafeClient

import com.codestates.chapter2.di.Menu;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

import java.util.List;

public class CafeClient {
    public static void main(String[] args) {
        GenericApplicationContext context =
                new AnnotationConfigApplicationContext(Config.class);
        MenuController controller = context.getBean(MenuController.class);


        List<Menu> menuList = controller.getMenus();
    }
}

CafeClient 에서는 전적으로 context라는 이름을 통해 전적으로 Config 클래스를 의존하고 있기때문에 모든 호출들이 Config 클래스에서 나오는 것에 의존적이다
따라서 Config 클래스에서 MenuService 가 new MenuServiceStub()로 정의되어 있기 때문에 사용되는 모든 MenuService들은
기존의 MenuService 인터페이를 참조하지 않고 이를 상속한 MenuServiceStub을 참조하게 된다.

MenuController

import java.util.List;

public class MenuController {
    private MenuService menuService;

    @Autowired
    public MenuController(MenuService menuService){
        this.menuService = menuService;
    }

    public List<Menu> getMenus(){
        return menuService.getMenuList();
    }
}

Config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = CafeClient.class)
public class Config {

    @Bean
    public MenuService getMenuService(){
        return new MenuServiceStub();
    }

    @Bean
    public MenuController getMenuController (MenuService menuService){
        return new MenuController(menuService); <<------------
    }
}
  • Config 클래스에서 MenuController 객체 생성을 정의해 두면 cafeClient class에서 이 객체를 애플리케이션 코드에 사용하게 된다.
  • 한마디로 Config 클래스에 정의해둔 MenuController 객체를 Spring의 도움을 받아서 CafeClient클래스에게 제공을 하고 있는 것이다.
  • 또한 config 클래스는 단순한 클래스가 아니라 Spring Framework의 영역에 해당하는 것이고 이 Config 클래스가 실제 애플리케이션의 핵심 로직에 관여하지 않고 있다. 온전히 Spring Framework의 영역인 것이다.

MenuService

  • 인터페이스
import com.codestates.chapter2.di.Menu;

import java.util.List;

public interface MenuService {
    List<Menu> getMenuList();
}

MenuServiceStub

  • 인터페이스 MenuService를 받음
import com.codestates.chapter2.di.Menu;

import java.util.List;

public class MenuServiceStub implements MenuService {

    @Override
    public List<Menu> getMenuList(){
        return List.of(
                new Menu(1,"아메리카노", 2500),
                new Menu(2, "카라멜 마끼아또", 4500),
                new Menu(3, "바닐라 라떼", 4500)
        );
    }
}

Menu

public class Menu {
    private long id;
    private String name;
    private int price;

    public Menu(long id, String name, int price){
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public long getId(){
        return id;
    }
    public String getName(){
        return name;
    }
    public int getPrice(){
        return price;
    }
}
profile
반갑습니다.

0개의 댓글