해결된 질문
작성
·
267
1
@Test
void configurationTest(){
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
MemberServiceImpl memberService = ac.getBean("memberService", MemberServiceImpl.class);
OrderServiceImpl orderService = ac.getBean("orderService", OrderServiceImpl.class);
MemberRepository memberRepository = ac.getBean("memberRepository", MemberRepository.class);
//모두 같은 인스턴스를 참고하고 있다.
System.out.println("memberService -> memberRepository = " + memberService.getMemberRepository());
System.out.println("orderService -> memberRepository = " + orderService.getMemberRepository());
System.out.println("memberRepository = " + memberRepository);
assertThat(memberService.getMemberRepository()).isSameAs(memberRepository);
assertThat(orderService.getMemberRepository()).isSameAs(memberRepository);
}
@Configuration
public class AppConfig {
@Bean
public MemberService memberService(){
System.out.println("call AppConfig.memberService");
return new MemberServiceImpl(memberRepository());
}
@Bean
public OrderService orderService(){
System.out.println("call AppConfig.orderService");
return new OrderServiceImpl(
memberRepository(),
discountPolicy()
);
}
@Bean
private static MemberRepository memberRepository() {
System.out.println("call AppConfig.memberRepository");
return new MemoryMemberRepository();
}
@Bean
private static DiscountPolicy discountPolicy() {
// return new FixDiscountPolicy();
return new RateDiscountPolicy();
}
}
실행 결과
call AppConfig.memberService
call AppConfig.memberRepository
call AppConfig.orderService
call AppConfig.memberRepository
call AppConfig.memberRepository
memberService -> memberRepository = MySpringStudy.core.v4.member.MemoryMemberRepository@30c93896
orderService -> memberRepository = MySpringStudy.core.v4.member.MemoryMemberRepository@59a008ba
memberRepository = MySpringStudy.core.v4.member.MemoryMemberRepository@338c99c8
java.lang.AssertionError:
Expecting actual:
MySpringStudy.core.v4.member.MemoryMemberRepository@30c93896
and:
MySpringStudy.core.v4.member.MemoryMemberRepository@338c99c8
to refer to the same object
강의에서 진행하신대로 스프링 컨테이너에서 빈을 주입받아서 사용했는데, 싱글톤으로 실행되지 않는 이유가 뭔지 궁금합니다..
감사합니다!