작성
·
262
0
안녕하세요 선생님.
도무지 원인을 모르겠어서 질문드립니다 ㅠㅠ
call AppConfig.memberService
call AppConfig.memberRepository
call AppConfig.orderService
이렇게 3번만 호출됨으로써 memberRepository가 여러번 생성되지 않음은 확인했습니다...
그런데
memberService -> memberRepository = hello.core.member.MemoryMemberRepository@5b068087
orderService -> memberRepositiory = hello.core.member.MemoryMemberRepository@6f152006
memberRepository = hello.core.member.MemoryMemberRepository@3a393455
왜 세개의 주소?가 다를까요..?ㅠㅠ
답변 2
1
안녕하세요. 백엔드님^^
AppConfig 코드를 잘 보셔야 합니다.
return new MemberServiceImpl(new MemoryMemberRepository());
-> return new MemberServiceImpl(memberRepository());
다른 코드도 모두 메서드 호출로 변경해주세요.
감사합니다.
0
아래는 테스트코드고
public class ConfigurationSingletonTest {
@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);
MemberRepository memberRepository1 = memberService.getMemberRepository();
MemberRepository memberRepository2 = orderService.getMemberRepository();
System.out.println("memberService -> memberRepository = "+ memberRepository1);
System.out.println("orderService -> memberRepositiory = "+ memberRepository2);
System.out.println("memberRepository = "+memberRepository);
Assertions.assertThat(memberService.getMemberRepository()).isSameAs(memberRepository);
Assertions.assertThat(orderService.getMemberRepository()).isSameAs(memberRepository);
}
}
아래는 AppConfig 코드입니다..
@Configuration
public class AppConfig {
@Bean
public MemberService memberService() {
System.out.println("call AppConfig.memberService");
return new MemberServiceImpl(new MemoryMemberRepository());
}
@Bean
public MemberRepository memberRepository() {
System.out.println("call AppConfig.memberRepository");
return new MemoryMemberRepository();
}
@Bean
public OrderService orderService() {
System.out.println("call AppConfig.orderService");
return new OrderServiceImpl(new MemoryMemberRepository(), new RateDiscountpolicy());
}
@Bean
public DiscountPolicy discountPolicy() {
return new RateDiscountpolicy();
}
}
감사합니다 ㅠㅠㅠ