싱글톤 빈과 프로토타입 빈을 함께 사용할때, 어떻게 하면 사용할 때마다 항상 새로운 프로토타입 빈을 생성할 수 있을까?
스프링 컨테이너에 요청
가장 간단한 방법은 싱글톤 빈이 프로토타입을 사용할 때마다 스프링 컨테이너에 새로 요청하는 것이다.
package hello.core.scope;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
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);
}
@Test
void singletonClientUsePrototype(){
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;
public ClientBean(PrototypeBean prototypeBean){
this.prototypeBean = prototypeBean;
}
public int logic(){
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 = ");
}
}
}
이전 시간의 코드이다.
의존관계를 외부에서 주입받는게 아니라 이렇게 직접 필요한 의존관계를 찾는 것을 Dependency Lookup이라고 한다.
그런데 이렇게 스프링의 애플리케이션 컨텍스트 전체를 주입받게 되면, 스프링 컨테이너에 종속적인 코드가 되고, 단위 테스트도 어려워진다.
지금 필요한 기능은 지정한 프로토타입 빈을 컨테이너에서 대신 찾아주는 DL 정도의 기능만 제공하는 무언가가 있으면 된다.
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();;
int count = prototypeBean.getCount();
return count;
}
}
실행해보면 getObject()를 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.
getObject()를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다.
JSR-330 Provider
마지막 방법은 javax.inject.Provider 라는 자바 표준을 사용하는 방법이다.
이방법을 사용하려면 라이브러리를 gradle에 추가해야한다.
@Scope("singleton")
static class ClientBean{
@Autowired
private Provider<PrototypeBean> prototypeBeanProvider;
public int logic(){
PrototypeBean prototypeBean = prototypeBeanProvider.get();
prototypeBean.addCount();;
int count = prototypeBean.getCount();
return count;
}
}
실행해보면 provider.get()을 통해 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다.
provider의 get() 을 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다.
자바 표준이고, 기능이 단순하므로 단위테스트를 만들거나 mock코드를 만들기 훨씬 쉽다.
프로토타입 빈을 언제 사용할까? 매번 사용할때 마다 의존 관계 주입이 완료된 새로운 객체가 필요하면 사용하면 된다.
그런데 실무에서 대부분의 문제는 싱글톤 빈으로 해결 할 수 있기에 쓰는 경우가 드물다고 한다.
'웹프로그래밍 > Spring 핵심 원리' 카테고리의 다른 글
52. request 스코프 예제 만들기 (0) | 2021.10.14 |
---|---|
51. 웹 스코프 (0) | 2021.10.14 |
49. 프로토타입 스코프 - 싱글톤 빈과 사용시 문제점 (0) | 2021.09.01 |
48. 프로토타입 스코프 (0) | 2021.08.23 |
47. 빈 스코프란? (0) | 2021.08.23 |