빈 스코프 [프로토타입 스코프]
스프링 빈이 스프링 컨테이너의 시작과 함께 생성되어 스프링 컨테이너가 종료될 때 까지 유지된다고 학습
스프링 빈이 기본적으로 싱글통 스코프로 생성되기 때문이다.
스코프는 빈이 존재할 수 있는 범위를 뜻한다.
스프링이 지원하는 다양한 스코프
- 싱글톤: 기본 스코프. 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프
- 프로토타입: 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입까지만 관여하고 더는 관리하지 않는 매우 짧은 범위의 스코프 (종료메서드 호출이 안됨)
- 웹 관련 스코프: 웹 관련 요청이 들어와야 쓸 수 있음
- request: 웹 요청이 들어오고 나갈 때까지 유지되는 스코프
- session: 웹 세션이 생성되고 종료될 때 까지 유지되는 스코프
- application: 웹의 서블릿 컨텍스와 같은 범위로 유지되는 스코프
싱글톤 스코프
싱글톤 스코프의 빈을 조회하면 스프링 컨테이너는 항상 같은 인스턴스의 스프링 빈을 반환한다.
- 싱글톤 스코프의 빈을 스프링 컨테이너에 요청
- 스프링 컨테이너는 본인이 관리하는 스프링 빈 반환
- 이후에 스프링 컨테이너에 같은 요청이 와도 같은 객체 인스턴스의 스프링 빈을 반환
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");
}
}
}
- init 한번 호출
- 같은 객체 반환
- 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"); // 프로토타입은 조회 직전에 생긴다. (init 호출)
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("SingletonBean.init");
}
@PreDestroy
public void destroy(){
System.out.println("SingletonBean.destroy");
}
}
}
- 조회할 때 새로운 객체 생성(init)
- 다른 객체 반환
- destroy 없음
- 싱글톤 빈은 스프링 컨테이너 생성 시점에 초기화 메서드가 실행되지만, 프로토타입 스토프의 빈은 스프링 컨테이너에서 빈을 조회할 때 생성되고, 초기화 메서드가 실행된다.
- 프로토타입 빈을 2번 조회했으므로 완전히 다른 스프링 빈이 생성되고, 초기화도 2번 실행되었다.
- 싱글톤 빈은 스프링 컨테이너가 관리하기 때문에 스프링 컨테이너가 종료될 때 빈의 종료 메서드가 실행되지만, 프로토타입 빈은 스프링 컨테이너가 생성과 의존관계 주입 그리고 초기화까지만 관여하고, 더는 관리하지 않는다.
- 따라서 프로토타입 빈은 스프링 컨테이너가 종료될 때 @PreDestroy 같은 종료 메서드가 전혀 실행되지 않는다.
🐤 프로토 타입 빈의 특징
- 스프링 컨테이너에 요청할 때 마다 새로 생성
- 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입 그리고 초기화까지만 관여
- 종료 메서드가 호출되지 않는다. (직접 호출하는 방법 뿐)
- 프로토타입 빈은 프로토타입 빈을 조회한 클라이언트가 관리해야 한다. 종료 메서드에 대한 호출도 클라이언트가 직접 해야한다.
프로토타입 스코프 - 싱글톤 빈과 함께 사용시 문제점
스프링 컨테이너에 프로토타입 스코프의 빈을 요청하면 항상 새로운 객체 인스턴스를 생성해 반환한다.
하지만 싱글톤 빈과 함께 사용할 때는 의도대로 동작하는지 주의가 필요하다.
1) 프로토타입 빈 직접 요청
public class SingletonWithPrototypeTest1 {
@Test
void prototypeFind(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
prototypeBean1.addCount();
Assertions.assertThat(prototypeBean1.getCount()).isEqualTo(1);
PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
prototypeBean2.addCount();
Assertions.assertThat(prototypeBean2.getCount()).isEqualTo(1);
}
@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");
}
}
}
2) 싱글톤 빈에서 프로토타입 빈 사용
clientBean이라는 싱글톤 빈이 의존관계 주입을 통해 프로토타입 빈을 주입받아서 사용하는 예
- clientBean은 싱글톤이므로, 스프링 컨테이너 생성 시점에 함께 생성되고, 의존관계 주입도 발생한다.
- 1. clientBean은 의존관계 자동 주입을 사용한다. 주입 시점에 스프링 컨테이너에 프로토 타입 빈을 요청한다.
- 2. 스프링 컨테이너는 프로토 타입 빈을 생성해 client에 반환한다. 프로토티압 빈의 count 필드 값은 0
- clientBean은 프로토타입 빈을 내부 필드에 보관한다.
- 클라이언트 A가 clientBean을 스프링 컨테이너에 요청해 받는다. 이는 싱글톤이라 항상 같은 clientBean이 반환된다.
- 3. 클라이언트 A는 clientBean.logic() 호출
- 4. clientBean은 prototypeBean의 addCount()를 호출해 프로토타입 빈의 count를 증가한다. 이때 count는 1
- 클라이언트 B는 clientBean을 스프링 컨테이너에 요청해 받는다. 싱글톤
- clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다. 주입 시점에 스프링 컨테이너에 요청해 프로토타입 빈이 새로 생성된 것이지 사용할 때마다 새로 생성되는 것이 아니다!
- 5. 클라이언트 B는 clientBean.logic()을 호출
- 6. clientBean은 prototypeBean의 addCount()를 호출. count는 2
public class SingletonWithPrototypeTest1 {
@Test
void singletonClientPrototype(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
ClientBean clientBean1 = ac.getBean(ClientBean.class);
int count1 = clientBean1.logic();
Assertions.assertThat(count1).isEqualTo(1);
ClientBean clientBean2 = ac.getBean(ClientBean.class);
int count2 = clientBean2.logic();
Assertions.assertThat(count2).isEqualTo(2);
}
@Scope("singleton")
static class ClientBean{
private final PrototypeBean prototypeBean; // 생성 시점에 주입이 끝난다.
@Autowired // 이때 프로토타입 빈을 생성한다. 1번만
public ClientBean(PrototypeBean prototypeBean) {
this.prototypeBean = prototypeBean;
}
public int logic(){
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");
}
}
}
- 원하는 프로토타입의 의도대로 돌아가지 않는다.
- 사용할 때마다 새로 생성되기 원한다.
- 스프링은 일반적으로 싱글톤 빈을 사용하므로, 싱글톤 빈이 프로토타입 빈을 사용하게 된다.
- 싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에, 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 계속 유지되는 것이 문제다.
🐤 싱글톤 빈과 함께 사용시 Provider로 문제 해결
싱글톤 빈과 프로토타입 빈을 함께 사용할 때, 어떻게 하면 사용할 때마다 새로운 프로토타입을 생성할 수 있을까?
1) 스프링 컨테이너에 요청
싱글톤 빈이 프로토타입을 사용할 때마다 스프링 컨테이너에 새로 요청
@Scope("singleton")
static class ClientBean{
@Autowired
private ApplicationContext ac;
public int logic(){
// 로직을 호출할 때마다 새로운 프로토타입 빈을 요청한다.
PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
prototypeBean.addCount();
return prototypeBean.getCount();
}
}
- ac.getBean()을 통해 항상 새로운 프로토타입 빈이 생성된다.
- 의존관계를 외부에서 주입(DI) 하는 것이 아니라 직접 필요한 의존관계를 찾는 것을 Dependency Lookup(DL) 의존관계 탐색 이라고 한다.
- 그런데 이렇게 스프링 애플리케이션 컨텍스트 전체를 주입받게 되면 스프링 컨테이너에 종속적인 코드가 되고, 단위 테스트도 어려워진다.
2) ObjectFactory, ObjectProvider
지정한 빈을 컨테이너에서 대신 찾아주는 DL 서비스를 제공하는 것이 ObjectProvider이다.
ObjectFactory > ObjectProvider
@Scope("singleton")
static class ClientBean{
@Autowired
private ObjectProvider<PrototypeBean> prototypeBeanProvider;
public int logic(){
PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
prototypeBean.addCount();
return prototypeBean.getCount();
}
}
- getObject를 실행하면 그때 새로 스프링 컨테이너에서 prototypeBean을 찾아 반환해준다.
- ObjectProvider의 getObject()를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다.
- 찾아주는 기능만 제공해준다. (DL)
- 스프링이 제공하는 기능을 사용하지만, 단순하므로 단위테스트를 만들거나 mock 코드를 만들기 쉬워진다.
🐤 특징
- ObjectFactory: 기능이 단순, 별도의 라이브러리 필요 없음, 스프링에 의존
- ObjectProvider: ObjectFactory 상속, 옵션, 스트림 처리 등 편의 기능이 많고, 별도의 라이브러리 필요 없음, 스프링에 의존
3) JSR-330 Provider
javax.inject.Provider라는 JSR-330 자바 표준을 사용하는 방법
라이브러리를 추가해야 한다.
implementation 'javax.inject:javax.inject:1'
@Scope("singleton")
static class ClientBean{
@Autowired
private Provider<PrototypeBean> prototypeBeanProvider;
public int logic(){
PrototypeBean prototypeBean = prototypeBeanProvider.get();
prototypeBean.addCount();
return prototypeBean.getCount();
}
}
- provider.get()을 통해 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.
- provider의 get()을 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아 반환한다.(DL)
- 자바 표준이고, 기능이 단순해 단위테스트를 만들거나 mock 코드를 만들기 쉽다.
🐤 특징
- get() 메서드 하나로 기능이 매우 단순
- 별도의 라이브러리가 필요하다.
- 자바 표준이므로 스프링이 아닌 다른 컨테이너에서도 사용할 수 있다.
✔️ 정리
- 프로토타입 빈을 언제 사용할까? 매번 사용할 때마다 의존관계 주입이 완료된 새로운 객체가 필요하면 사용하면 된다.
- 그런데 매우 드물다.
- ObjectProvider, JSR330 Provider 등은 프로토타입 뿐만 아니라 DL이 필요한 경우 언제든지 사용 가능하다.