Spring 시리즈는 혼자 공부하며 기록으로 남기고, 만약 잘못 학습 한 지식이 있다면 공유하며 피드백을 받고자 작성합니다.
스프링에 대해 깊게 공부해보고자 인프런의 김영한 강사님께서 강의를 진행하시는 (스프링 핵심 원리 - 기본편) 강의를 수강하며 정리하는 글입니다.
혹여나 글을 읽으시며 잘못 설명된 부분이 있다면 지적 부탁드리겠습니다.
싱글톤 빈 요청

싱글톤 테스트 코드
public class SingletonTest {
@Test
void singletonBeanFind() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SingletonBean.class);
SingletonBean singletonBean1 = ac.getBean(SingletonBean.class);
SingletonBean singletonBean2 = ac.getBean(SingletonBean.class);
System.out.println("singletonBean1 = " + singletonBean1);
System.out.println("singletonBean2 = " + singletonBean2);
Assertions.assertThat(singletonBean1).isSameAs(singletonBean2);
ac.close();
}
@Scope("singleton")
static class SingletonBean {
@PostConstruct
public void init() {
System.out.println("SingletonBean.init");
}
@PreDestroy
public void destroy() {
System.out.println("SingletonBean.destroy");
}
}
}
싱글톤 테스트 결과
SingletonBean.init
singletonBean1 = hello.core.scope.SingletonTest$SingletonBean@3591009c
singletonBean2 = hello.core.scope.SingletonTest$SingletonBean@3591009c
19:27:07.315 [Test worker] DEBUG o.s.c.a.AnnotationConfigApplicationContext -- Closing
SingletonBean.destroy
프로토타입 빈 요청


살짝콩 정리
@PreDestroy같은 종료 메서드는 호출되지 않는다.프로토타입 테스트 코드
public class PrototypeTest {
@Test
void prototypeBeanFind() {
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);
Assertions.assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
//prototypeBean1.destroy();
//prototypeBean2.destroy();
ac.close();
}
@Scope("prototype")
static class PrototypeBean {
@PostConstruct
public void init() {
System.out.println("PrototypeBean.init");
}
@PreDestroy
public void destroy() {
System.out.println("PrototypeBean.destroy");
}
}
}
@PreDestroy 애노테이션이 붙은 메서드는 호출이 될 리가 없다.프로토타입 테스트 결과
find prototypeBean1
PrototypeBean.init
find prototypeBean2
PrototypeBean.init
prototypeBean1 = hello.core.scope.PrototypeTest$PrototypeBean@3591009c
prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@5398edd0
19:35:17.475 [Test worker] DEBUG o.s.c.a.AnnotationConfigApplicationContext -- Closing
.destroy() 코드를 작성해야한다.프로토타입 빈 특징 정리