AppConfig 및 MemberApp, OrderApp을 Spring 으로 전환해보자
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MemberService memberService(){
return new MemberServiceImpl(memberRepository());
}
@Bean
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
@Bean
public OrderService orderService(){
return new OrderServiceImpl(memberRepository(),discountPolicy());
}
@Bean
public DiscountPolicy discountPolicy(){
return new RateDiscountPolicy();
}
}
AppConfig 를 @Configuration으로
나머지 구현 객체 인스턴스 할당하는 부분을 모두 @Bean으로 등록한다.
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
MemberService memberService = applicationContext.getBean("memberService",MemberService.class);
그리고 각 Application 코드는 ApplicationContext를 통해서 AnnotationConfigApplicationContext 생성하고
AnnotationConfigApplicationContext에서 AppConfig에서 생성했던 구현 객체들을 꺼내온다
APplicationContext 를 스프링 컨테이너 라고 한다.
기존에는 직접 AppConfig를 사용해서 객체를 생성하고 DI를 했지만 이제는 스프링 컨테이너가 대신 한다.
@Configuration이 붙은 AppConfig의 설정 정보를 사용
@Bean이 붙은 모든 메서드를 호출해서 반환된 객체를 스프링 컨테이너에 등록해놓음
등록된 객체를 모두 스프링 빈이라고 함
스프링 빈이 붙은 객체를 getBean 메서드를 통해서 이름을 통해서 가져온다
즉 스프링 컨테이너가 객체를 등록하고 꺼내오는 방식으로 바꾸는 것
그럼 어떤 장점이 있길래 이렇게 쓰는거지??
다음 챕터에서 상세하게 알아보자!