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을 참조하게 된다.
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();
}
}
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의 영역인 것이다.
import com.codestates.chapter2.di.Menu;
import java.util.List;
public interface MenuService {
List<Menu> getMenuList();
}
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)
);
}
}
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;
}
}