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

권정익님의 프로필 이미지

작성한 질문수

스프링 핵심 원리 - 기본편

섹션 10. 빈스코프 질문 2

해결된 질문

24.06.13 18:01 작성

·

85

0

public class PrototypeTest {


    @Test
    void PrototypeBeanTest() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);

        System.out.println("find PrototypeBean1");
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        System.out.println("find PrototypeBean2");
        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);

        System.out.println("prototypeBean1 = " + prototypeBean1);
        System.out.println("prototypeBean2 = " + prototypeBean2);

        assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
    }

    static class PrototypeBean {

        @PostConstruct
        public void init() {
            System.out.println("PrototypeBean.init");
        }

        @PreDestroy
        public void destroy() {
            System.out.println("PrototypeBean.destroy");
        }
    }
}

결과

prototypeBean1 = hello.core.scope.PrototypeTest$PrototypeBean@29caf222

prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@29caf222

 

강의에서 프로토타입 스코프를 코드로 작성하고 실행하는 도중 깜빡하고 스코프 애노테이션을 넣는 걸 깜빡했습니다.

그런데 prototypeBean1 과 prototypeBean2 의 참조값이 같게 나왔습니다.

@Configuration을 적지 않았는데 왜 싱글톤이 적용이 된 건지 잘 이해가 가지 않습니다...


AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);

위 코드에서 AnnotationConfigApplicationContext를 생성할 때 PrototypeBean 정보를 넘겨주면 내부적으로 빈 등록 과정이 진행되기 때문입니다.

감사합니다.

라고 답변을 받았는데,

답변에 대한 질문: PrototypeBean.class의 정보를 넘겨주는데 PrototypeBean 클래스에 @Configuration을 적지 않으면 싱글톤이 적용이 안되는 거 아닌가요??ㅠㅠ

답변 1

1

David님의 프로필 이미지

2024. 06. 14. 00:47

안녕하세요. 권정익님, 공식 서포터즈 David입니다.

이전 글 댓글로 답변 남겨두었습니다.

감사합니다.