9 - 프로토 타입 스코프를 싱글톤 빈과 함께 사용시 문제점 강의중 질문
미해결
스프링 핵심 원리 - 기본편
질문 1. 아래코드에서 ClientBean 이 내부 메서드에서 prototypeBean 을 사용할 수 있는 이유? static class ClientBean{ ... } 의 코드에서는 스프링 빈으로 prototypeBean 을 등록하는 부분이 없는데 어떻게 logic() 메소드에서 prototypeBean.addCount(); 를 사용할 수 있는 것인가요? 🤔 제 생각에는 void singletonClientUsePrototype() 의 코드인 AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class); 으로 빈으로 등록이 되는 것 같아서 코드를 다음과 같이 수정 후 실행해 보았습니다. AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class); 👉 그러자 실행이 안되는 것을 확인 할 수 있었습니다. 질문 2. singletonClientUsePrototype() 메소드에서 등록된 빈이 ClientBean에 어떻게 영향을 주는 것인가요? 🤔 ClientBean 코드의 ApplicationContext applicationContext; 의 의존성 주입을 통해 이루어지는 것 같은데 이 코드에서는 어떤 것이 applicationContext 에 해당되는 것인가요..? 따로 해당 인스턴스타입으로 등록된 빈이 없는 것 같은데 헷갈립니다ㅜㅜ public class SingletonWithPrototypeTest1 { @Test void singletonClientUsePrototype(){ AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class); ClientBean client1 = ac.getBean(ClientBean.class); int count1 = client1.logic(); assertThat(count1).isEqualTo(1); System.out.println("count1 = " + count1); ClientBean client2 = ac.getBean(ClientBean.class); int count2 = client2.logic(); System.out.println("count2 = " + count2); assertThat(count2).isEqualTo(1); } @Scope("singleton") static class ClientBean { @Autowired ApplicationContext applicationContext; public int logic() { PrototypeBean prototypeBean = applicationContext.getBean(PrototypeBean.class); prototypeBean.addCount(); return prototypeBean.getCount(); } } @Scope("prototype") static class PrototypeBean { private int count = 0; public void addCount() { count++; } public int getCount() { return count; } @PostConstruct public void init() { System.out.println("PrototypeBean.init" + this); } @PreDestroy public void destroy() { System.out.println("PrototypeBean.destroy"); } } }
- spring
- 객체지향
- 프로토타입
- 싱글톤타입





