빈 스코프란 해당 빈이 어떤 범위 내에서 생성되고, 관리되며, 존재하는지를 정의한 것으로 빈의 생명주기와 밀접하게 연관되어 있다.
@PreDestroy 같은 종료 메서드가 호출되지 않는다.

스프링 컨테이너는 프로토타입 빈을 생성하고 의존관계 주입 후, 초기화까지만 처리한다.
void singletonBeanTest() {
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(PrototypeBean.class);
System.out.println("find bean1");
PrototypeBean bean1 = ac.getBean(PrototypeBean.class);
System.out.println("find bean2");
PrototypeBean bean2 = ac.getBean(PrototypeBean.class);
System.out.println("bean1 : " + bean1);
System.out.println("bean2 : " + bean2);
Assertions.assertThat(bean1).isNotSameAs(bean2);
bean1.destroy();
bean2.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");
}
}
실행결과
find bean1
PrototypeBean.init
find bean2
PrototypeBean.init
bean1 : dev.highright96.core.scope.PrototypeTest$PrototypeBean@1efe439d
bean2 : dev.highright96.core.scope.PrototypeTest$PrototypeBean@be68757
PrototypeBean.destroy
PrototypeBean.destroy
@PreDestory 같은 종료 메서드가 전혀 실행되지 않는다. 위의 결과는 직접 destroy 메서드를 호출한 결과이다.싱글톤과 프로토타입 스코프를 함께 사용시( 정확히는 싱글톤 안에서 프로토타입 사용시) 이다.
스프링은 일반적으로 싱글톤 빈을 사용한다. 싱글톤 빈이 프로토타입 빈을 사용하게 되낟.
싱글톤 빈은 생성시점에만 의존관계 주입을 받기 때문에, 프로토 타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 유지되는 것이 문제다.

우리가 원하는 결과는 A, B 모두 count=1 이다. 하지만 결과는 클라이언트A는 1 클라이언트B는 2가 저장된다.
그 이유는 싱글톤 빈이 내부에 가지고 있는 프로토타입 빈은 이미 과거(싱글톤 빈이 생성될때)에 주입이 끝난 빈이기 때문에 이후에 새로 생성될 일이 없기 때문이다. 따라서 프로토타입 빈의 특징을 잃어버린다.
싱글톤 빈과 프로토타입 빈을 함께 사용할 때, 어떻게 하면 사용할 때 마다 항상 새로운 프로토타입 빈을 생성할 수 있을까?
필요한 의존관계를 찾는 Dependency Lookup(DL) 의존관계 조회를 제공하는 무언가를 사용하면 된다.
public class PrototypeProviderTest {
@Test
void providerTest() {
AnnotationConfigApplicationContext ac = new
AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
ClientBean clientBean1 = ac.getBean(ClientBean.class);
int count1 = clientBean1.logic();
assertThat(count1).isEqualTo(1);
ClientBean clientBean2 = ac.getBean(ClientBean.class);
int count2 = clientBean2.logic();
assertThat(count2).isEqualTo(1);
}
static class ClientBean {
***@Autowired
private ApplicationContext ac;
public int logic() {
PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
prototypeBean.addCount();
int count = prototypeBean.getCount();
return count;
}***
}
@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");
}
}
}
이렇게 스프링의 애플리케이션 컨텍스트 전체를 주입받게 되면, 스프링 컨테이너에 종속적인 코드가 되고, 단위테스트가 어려워진다.
지정한 프로토타입 빈을 컨테이너에서 대신 찾아주는 DL 정도의 기능만 제공하는 무언가 있다.
지정한 빈을 컨테이너에서 대신 찾아주는 DL 서비스를 제공하는 것이 바로 ObjectProvider 이다. 과거에는 ObjectFactory가 있었는데 ObjectProvider가 기능이 더 많다.
@Autowired
private ObjectProvider<PrototypeBean> prototypeBeanProvider;
public int logic() {
PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
prototypeBean.addCount();
int count = prototypeBean.getCount();
return count;
}
prototypeBeanProvider.getObject() 을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.ObjectProvider 의 getObject() 를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. (DL)javax.inject.Provider 라는 JSR-330 자바 표준을 사용하는 방법이다. 스프링 부트 3.0에서는 jakarta.inject.Provider 를 사용한다.
스프링 부트 3.0 jakarta.inject.Provider 사용
@Autowired
private Provider<PrototypeBean> provider;
public int logic() {
PrototypeBean prototypeBean = provider.get();
prototypeBean.addCount();
int count = prototypeBean.getCount();
return count;
}
get() 메소드 하나로 기능이 매우 단순해진다.웹 스코프는 웹 환경에서만 동작하며 프로토타입과 다르게 스프링이 스코프의 종료시점까지 관리한다. 따라서 종료 메서드가 호출된다.
request: HTTP 요청 하나가 들어오고 나갈 때 까지 유지되는 스코프, 각각의 HTTP 요청마다 별도의 인스턴스가 생성되고 관리된다.session: HTTP Session과 동일한 생명주기를 가지는 스코프apllication: 서블릿 컨텍스트와 동일한 생명주기를 가지는 스코프websocket: 웹 소켓과 동일한 생명주기를 가지는 스코프
스프링 핵심 원리-기본편 을 마치게 되었다. 생소한 개념, 헷갈리는 용어 투성이었지만, 욕심보다 70% 정도 이해만 되면 넘어가면서 진도를 맞추기 위해 노력했다. 아직 백엔드 개발자로는 너무 부족하다. 열심히 하자…