공부/Spring
[Spring] 빈 스코프 - 프로토타입 스코프와 싱글톤 빈과 함께 사용시 문제점
sesam
2024. 1. 2. 19:26
728x90
프로토타입 스코프 - 싱글톤 빈과 함께 사용시 문제점
스프링 컨테이너에 프로토타입 스코프의 빈을 요청하면 항상 새로운 객체 인스턴스를 생성해서 반환한다.
하지만 싱글 톤 빈과 함께 사용할 때는 의도한 대로 잘 동작하지 않으므로 주의해야 한다.
먼저 스프링 컨테이너에 프로토타입 빈을 직접 요청하는 예제를 보자.
프로토타입 빈 직접 요청
스프링 컨테이너에 프로토타입 빈 직접 요청1
스프링 컨테이너에 프로토타입 빈 직접 요청2
코드확인
public class SingletonWithPrototypeTest1 {
@Test
void prototypeFind() {
AnnotationConfigApplicationContext ac = new
AnnotationConfigApplicationContext(PrototypeBean.class);
// prototypeBean1
PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
prototypeBean1.addCount();
assertThat(prototypeBean1.getCount()).isEqualTo(1);
// prototypeBean2
PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
prototypeBean2.addCount();
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");
}
}
}
싱글톤 빈에서 프로토타입 빈 사용
clientBean 이라는 싱글톤 빈이 의존관계 주입을 통해서 프로토타입 빈을 주입받아서 사용하는 예
싱글톤에서 프로토타입 빈 사용1
싱글톤에서 프로토타입 빈 사용2
싱글톤에서 프로토타입 빈 사용3
클라이언트 B가 logic을 호출하면 count = 1이 아니라 2가 나온다.
스프링은 일반적으로 싱글톤 빈을 사용하므로, 싱글톤 빈이 프로토타입 빈을 사용하게 된다.
그런데 싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에, 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 계속 유지되는 것 이 문제다.
왜 문제가 되냐면,
프로토 타입을 쓰는 이유는 프로토타입 빈을 주입 시점에만 새로 생성하는게 아니라, 사용할 때마다 새로 생성해서 사용하는 것을 원할 것이다.
참고: 여러 빈에서 같은 프로토타입 빈을 주입 받으면, 주입 받는 시점에 각각 새로운 프로토타입 빈이 생성된다.
예를 들어서 clientA, clientB가 각각 의존관계 주입을 받으면 각각 다른 인스턴스의 프로토타입 빈을 주입 받는다.
clientA → prototypeBean@x01
clientB → prototypeBean@x02
물론 사용할 때 마다 새로 생성되는 것은 아니다.