빈 스코프란 말 그대로 빈이 존재할 수 있는 범위를 뜻한다
@Scope("prototype")
@Component
public class HelloBean{
...
}
빈 스코프의 지정은 다음과 같이 @Scope(지정타입)
으로 지정해주면 된다
- 스프링 컨테이너는 프로토타입 빈에 대해서는 생성, 의존관계 주입, 초기화까지만 처리한다.
- 스프링 컨테이너는 클라이언트에 빈을 반환하고, 이후 생성된 프로토타입 빈을 관리하지 않는다.
- 프로토타입 빈을 관리할 책임은 프로토타입 빈을 받은 클라이언트에게 있어
@PreDestroy
같은 종료 메서드가 호출되지 않는다.
package Hello.core.scope;
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;
import static org.assertj.core.api.Assertions.*;
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");
}
}
}
package Hello.core.scope;
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;
import static org.assertj.core.api.Assertions.assertThat;
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);
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");
}
}
}
@PreDestroy
같은 종료 메소드가 실행되지 않음
- 스프링 컨테이너에 요청할 때마다 새로 생성
- 스프링 컨테이너는 프로토타입 빈의 생성, 의존관계 주입, 초기화까지만 관여
- 종료 메소드가 호출되지 않음
- 프로토타입 빈은 프로토타입 빈을 조회한 클라이언트가 관리하고 종료 메소드 호출도 클라이언트가 직접 해야함
스프링 컨테이너에 프로토타입 스코프의 빈을 요청 시 항상 새로운 객체 인스턴스를 생성해 반환하지만, 싱글톤 빈과 함께 사용할 때는 의도한 대로 잘 동작하지 않으므로 주의해야한다.
먼저 스프링 컨테이너에 프로토타입 빈을 직접 요청하는 예제를 보자.
addCount()
를 호출하면서 count 필드를 +1addCount()
를 호출하면서 count 필드를 +1
public class SingletonWithPrototypeTest1 {
@Test
void prototypeFind(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
prototypeBean1.addCount();
assertThat(prototypeBean1.getCount()).isEqualTo(1);
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
이라는 싱글톤 빈이 의존관계 주입을 통해 프로토타입 빈을 주입받아야하는 예를 보자
clientBean
은 싱글톤이므로, 스프링 컨테이너 생성 시점에 함께 생성과 의존관계 주입 발생clientBean
은 의존관계 자동 주입을 사용해 주입 시점에 스프링 컨테이너에 프로토타입을 요청clientBean
에 반환, 프로토타입 빈의 count 필드값은 0clientBean
은 프로토타입 빈의 참조값을 내부 필드에 보관clientBean
을 스프링 컨테이너에 요청해서 반환받음, 싱글톤이므로 항상 같은 clientBean
을 반환clientBean.logic()
을 호출clientBean
은 prototypeBean의 addCount()
를 호출해 프로토타입 빈의 count를 증가시키고 count값이 1이됨clientBean
을 스프링 컨테이너에 요청, 싱글톤이므로 항상 같은 clientBean
이 반환clientBean.logic()
을 호출clientBean
은 prototypeBean의 addCount()
를 호출해 프로토타입의 count를 증가시킴, 원래 count값이 1이었으므로 2가 됨package Hello.core.scope;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import static org.assertj.core.api.Assertions.*;
public class SingletonWithPrototypeTest1 {
@Test
void singletonClientUsePrototype() {
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(2);
}
static class ClientBean {
private final PrototypeBean prototypeBean;
@Autowired
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");
}
}
}
스프링은 일반적으로 싱글톤 빈을 사용하므로, 싱글톤 빈이 프로토타입 빈을 사용하게된다. 그런데 싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에, 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 계속 유지되는 것이 문제다.
우리는 프로토타입 빈을 주입 시점에만 새로 생성하는게 아닌, 사용할 때 마다 새로 생성해서 사용하는 것을 원할 것이다.
여러 빈에서 같은 프로토타입 빈을 주입 받으면, 주입 받는 시점에 각각 새로운 프로토타입 빈이 생성된다. 예를 들어서 clientA, clientB가 각각 의존관계 주입을 받으면 각각 다른 인스턴스의 프로토타입 빈을 주입받는다.
clientA -> prototypeBean@x01
clientB -> prototypeBean@x02
물론 사용할 때 마다 새로 생성되는 것은 아니다.
싱글톤 빈과 프로토타입 빈을 함께 사용할 때, 어떻게 하면 사용할 때 마다 항상 새로운 프로토타입 빈을 생성할 수 있을까?
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");
}
}
}
ac.getBean()
을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다DL의 기능을 제공하는 것이 바로 ObjectProvider
이다. 과거에는 ObjectFactory
가 있었는데 여기에 기능을 좀 더 추가한게 ObjectProvider
이므로 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()
를 호출시 스프링 컨테이너를 통해 해당 빈을 찾아 반환ObjectProvider
는 지금 딱 필요한 DL 정도의 기능만 제공JSR-330 자바 표준(인터페이스의 모음)을 사용하는 방법, 스프링 부트 3.0은 jakarta.inject.Provider
사용
javax.inject:javax.inject:1
jakarta.inject:jakarta.inject-api:2.0.1
get()
메소드를 가진다@Autowired
private Provider<PrototypeBean> provider;
public int logic() {
PrototypeBean prototypeBean = provider.get();
prototypeBean.addCount();
int count = prototypeBean.getCount();
return count;
}
provider.get()
를 통해 항상 새로운 프로토타입 빈이 생성provider
의 get()
를 호출시 스프링 컨테이너를 통해 해당 빈을 찾아 반환(DL)provider
는 지금 딱 필요한 DL 정도의 기능만 제공get()
메소드 하나로 기능이 매우 단순@Lookup
애노테이션을 사용하는 방법도 있지만, 이전 방법들로 충분하고, 고려해야할 내용도 많아서 생략
- 매번 사용할 때마다 의존관계 주입이 완료된 새로운 객체가 필요할 때 프로토타입 빈을 사용한다
- 실무에서는 싱글톤 빈으로 대부분을 해결할 수 있기 때문에 프로토타입 빈을 직접적으로 사용하는 일은 드물다
- ObjectProvider, JSR-330 Provider은 프로토타입 뿐만 아니라 DL이 필요한 경우는 언제든 사용할 수 있다
- JSR-330 Provider와 ObjectProvider 중 무엇을 사용할 지 고민이 된다면 코드를 스프링이 아닌 다른 컨테이너에서도 사용할 수 있어야 한다면 JSR-330 Provider을 사용해야한다
- 자바 표준과 스프링의 기능이 겹칠 때, 다른 컨테이너를 사용할 일이 없다면 스프링이 제공하는 기능을 사용하면 된다
implementation 'org.springframework.boot:spring-boot-starter-web'
다음을 build.gradle에 추가해준다
이제 hello.core.CoreApplication
을 실행하면 다음과 같이 실행된다
- 스프링 부트는 웹 라이브러리가 없으면
AnnotationConfigApplicationContext
을 기반으로 애플리케이션을 구동한다. 웹 라이브러리가 추가되면 웹과 관련된 추가 설정과 환경들이 필요하므로AnnotationConfigServletWebServerApplicationContext
을 기반으로 애플리케이션을 구동한다.- 기본 포트인 8080 포트를 다른 곳에서 사용중이어서 오류가 발생하면 9090 포트로 변경하기 위해 다음의 경로에 설정을 추가해줘야 한다
main/resources/application.properties
<- 경로
server.port=9090
request 스코프는 동시에 여러 HTTP 요청이 와서 정확히 어떤 요청이 남긴 로그인지 구분하기 어려울 때 사용한다
다음과 같이 로그가 남도록 request 스코프를 활용해서 추가 기능을 개발해볼 것이다
[d06b992f...] request scope bean create
[d06b992f...][http://localhost:8080/log-demo] controller test
[d06b992f...][http://localhost:8080/log-demo] service id = testId
[d06b992f...] request scope bean close
[UUID][requestURL]{message}
package Hello.core.common;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.UUID;
@Component
@Scope(value = "request")
public class MyLogger {
private String uuid;
private String requestURL;
public void setRequestURL(String requestURL){
this.requestURL = requestURL;
}
public void log(String message){
System.out.println("[" + uuid + "]" + "[" + requestURL + "] " + message);
}
@PostConstruct
public void init(){
uuid = UUID.randomUUID().toString();
System.out.println("[" + uuid + "] request scope bean create:" + this);
}
@PreDestroy
public void close(){
System.out.println("[" + uuid + "] request scope bean close:" + this);
}
}
@Scope(value = "request")
를 사용해서 request 스코프로 지정, 이제 이 빈은 HTTP 요청 당 하나씩 생성되고, HTTP 요청이 끝나는 시점에 소멸된다@PostConstruct
초기화 메소드를 사용해 uuid를 생성해 저장해둔다. 이 빈은 HTTP 요청 당 하나씩 생성되므로, uuid를 저장해두면 다른 HTTP 요청과 구분할 수 있다.@PreDestroy
를 사용해서 종료 메시지를 남긴다.package Hello.core.web;
import Hello.core.common.MyLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequiredArgsConstructor
public class LogDemoController {
private final LogDemoService logDemoService;
private final MyLogger myLogger;
@RequestMapping("log-demo")
@ResponseBody
public String logDemo(HttpServletRequest request) throws InterruptedException {
String requestURL = request.getRequestURL().toString();
System.out.println("myLogger = " + myLogger.getClass());
myLogger.setRequestURL(requestURL);
myLogger.log("controller test");
Thread.sleep(1000);
logDemoService.logic("testId");
return "OK";
}
}
http://localhost:8080/log-demo
requestURL을 MyLogger에 저장하는 부분은 컨트롤러보다는 공통 처리가 가능한 스프링 인터셉터나 서블릿 필터 같은 곳을 활용하는 것이 좋다.
스프링 웹에 익숙하다면 인터셉터를 사용해 구현해보자.
package Hello.core.web;
import Hello.core.common.MyLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class LogDemoService {
private final MyLogger myLogger;
public void logic(String id) {
myLogger.log("service id = " + id);
}
}
[d06b992f...] request scope bean create
[d06b992f...][http://localhost:8080/log-demo] controller test
[d06b992f...][http://localhost:8080/log-demo] service id = testId
[d06b992f...] request scope bean close
Error creating bean with name 'myLogger': Scope 'request' is not active for the
current thread; consider defining a scoped proxy for this bean if you intend to
refer to it from a singleton;
package Hello.core.web;
import Hello.core.common.MyLogger;
import Hello.core.logdemo.LogDemoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequiredArgsConstructor
public class LogDemoController {
private final LogDemoService logDemoService;
private final ObjectProvider<MyLogger> myLoggerProvider;
@RequestMapping("log-demo")
@ResponseBody
public String logDemo(HttpServletRequest request) {
String requestURL = request.getRequestURL().toString();
MyLogger myLogger = myLoggerProvider.getObject();
myLogger.setRequestURL(requestURL);
myLogger.log("controller test");
logDemoService.logic("testId");
return "OK";
}
}
package Hello.core.logdemo;
import Hello.core.common.MyLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class LogDemoService {
private final ObjectProvider<MyLogger> myLoggerProvider;
public void logic(String id) {
MyLogger myLogger = myLoggerProvider.getObject();
myLogger.log("service id = " + id);
}
}
ObjectProvider.getObject()
를 호출하는 시점까지 request 스코프 빈의 생성을 지연할 수 있다.ObjcetProvider.getObject()
를 LogDemoController, LogDemoService에서 각각 한 번씩 따로 호출해도 같은 HTTP 요청이면 같은 스프링 빈이 반환된다!@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyLogger {
}
proxyMode = ScopedProxyMode.TARGET_CLASS
를 추가해준다.TARGET_CLASS
를 선택INTERFACES
를 선택나머지 코드를 Provider 사용 이전으로 돌려두겠다.
package Hello.core.web;
import Hello.core.common.MyLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequiredArgsConstructor
public class LogDemoController {
private final LogDemoService logDemoService;
private final MyLogger myLogger;
@RequestMapping("log-demo")
@ResponseBody
public String logDemo(HttpServletRequest request) throws InterruptedException {
String requestURL = request.getRequestURL().toString();
System.out.println("myLogger = " + myLogger.getClass());
myLogger.setRequestURL(requestURL);
myLogger.log("controller test");
Thread.sleep(1000);
logDemoService.logic("testId");
return "OK";
}
}
package Hello.core.web;
import Hello.core.common.MyLogger;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class LogDemoService {
private final MyLogger myLogger;
public void logic(String id) {
myLogger.log("service id = " + id);
}
}
System.out.println("myLogger = " + myLogger.getClass());
를 통해 주입된 myLogger를 확인해보자
@Scope
의 proxyMode = ScopedProxyMode.TARGET_CLASS)
를 설정하면 스프링 컨테이너는 CGLIB라는 바이트코드를 조작하는 라이브러리를 사용해, MyLogger를 상속받은 가짜 프록시 객체를 생성한다.MyLogger$$EnhancerBySpringCGLIB
이라는 클래스로 만들어진 객체가 대신 등록된 것을 확인할 수 있다.myLogger
라는 이름으로 진짜 대신에 이 가짜 프록시 객체를 등록한다ac.getBean("myLogger", MyLogger.class)
로 조회해도 프록시 객체가 조회되는 것을 확인할 수 있다.myLogger.logic()
을 호출하면 사실은 가짜 프록시 객체의 메소드를 호출한 것 이다myLogger.logic()
을 호출한다
- CGLIB라는 라이브러리로 내 클래스를 상속받은 가짜 프록시 객체를 만들어서 주입한다
- 이 가짜 프록시 객체는 실제 요청이 오면 그때 내부에서 실제 빈을 요청하는 위임 로직이 들어있다
- 가짜 프록시 객체는 실제 request 스코프와는 관계가 없다, 그냥 가짜이고 내부에 단순한 위임 로직만 있고 싱글톤처럼 동작한다
- 프록시 객체 덕분에 클라이언트는 싱글톤 빈을 사용하듯이 편리하게 request 스코프를 사용할 수 있다
- 사실 Provider를 사용하든, 프록시를 사용하든 핵심 아이디어는 진짜 객체 조회를 꼭 필요한 시점까지 지연처리 한다는 점이다
- 단지 애노테이션 설정 변경만으로 원본 객체를 프록시 객체로 대체가능, 이것이 바로 다형성과 DI컨테이너가 가진 큰 강점이다(클라이언트 코드를 고치지 않아도 된다)
- 꼭 웹 스코프가 아니어도 프록시는 사용할 수 있다