인프런 커뮤니티 질문&답변

백엔드가 하고싶어요님의 프로필 이미지
백엔드가 하고싶어요

작성한 질문수

스프링 핵심 원리 - 기본편

싱글톤 적용이 안된 이유가 궁금합니다.

해결된 질문

작성

·

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

 

강의에서 진행하신대로 스프링 컨테이너에서 빈을 주입받아서 사용했는데, 싱글톤으로 실행되지 않는 이유가 뭔지 궁금합니다..

답변 1

1

잘모르지만 메소드들이 static으로 선언되서 그런거같아요
private static을 지우고 public으로 바꿔주시면 잘될거에요

감사합니다!

백엔드가 하고싶어요님의 프로필 이미지
백엔드가 하고싶어요

작성한 질문수

질문하기