스프링/스프링 기본이론
프로토타입 스코프
chanhee01
2023. 2. 1. 23:05
빈 스코프는 빈이 생성되고부터 소멸할 때까지의 단계이다. 프로토타입 스코프는 빈을 생성한 다음에 스프링에서 관리해주는 것이 아니고, 사용자 요청이 있을 때마다 새로운 객체를 생성해서 사용자에게 넘겨주고 끝낸다.
즉, 생성되고 이후는 사용자에게 빈의 권한이 있고, 그렇기 때문에 @PreDstroy도 호출되지 않는다.
싱글톤의 경우
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);
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");
}
}
}
빈의 스코프가 싱글톤인 경우에는 init, destroy 둘 다 제대로 호출될 것이고, 싱글톤이기 때문에 2개의 빈도 같은 빈일 것이다.
프로토타입 스코프
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);
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");
}
}
}
프로토타입은 싱글톤처럼 하나의 객체로 관리되는 것이 아니기때문에 빈마다 init을 호출하게 될 것이고, 빈을 출력해보면 각각의 빈의 참조값이 다르다. 또한 생성만하고 관여를 하지 않기 때문에 destroy를 호출해주지 않는다.