빙응의 공부 블로그

[Spring]스프링 핵심 원리 - 빈 스코프 본문

Spring/인프런_개념

[Spring]스프링 핵심 원리 - 빈 스코프

빙응이 2023. 12. 29. 15:15

📝빈 스코프

지금까지 학습에서 스프링 빈이 스프링 컨테이너가 생성될 때 함께 생성되어 스프링 컨테이너가 종료될 때 같이 종료된다고 학습하였다. 

이것은 스프링 빈이 기본적으로 싱글톤 스코프로 생성되기 때문이다. 

스코프는 번역 그대로 빈이 존재할 수 있는 범위를 뜻한다.

 

스프링의 스코프들
  • 싱글톤 : 기본 스코프, 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프이다.
  • 프로토타입 : 요청할 때마다 새로운 빈 인스턴스를 생성하며 의존관계 주입까지만 한다. 
  • 웹 관련 스코프
    • request : 웹 요청이 들어오고 나갈때까지 유지되는 스코프
    • session : 웹 세션이 생성되고 종료될 떼 까지 유지되는 스코프
    • application : 웹의 서블릿 컨텍스트와 같은 범위로 유지되는 스코프 

 

 

 

📝프로토타입 스코프 

@Scope("prototype")
@Component
public class HelloBean {}

싱글톤 스코프의 빈을 조회하면 스프링 컨테이너는 항상 같은 인스턴스의 스프링 빈을 반환한다.

반면에 프로토타입 스코프를 스프링 컨테이너에 조회하면 항상 새로운 인스턴스를 생성해 반환한다.

 

싱글톤 스코프

서비스를 요청하면 항상 같은 인스턴스를 반환한다. 

 

프로토타입 스코프

서비스를 요청하면 새로운 인스턴스를 생성해 반환하며 스프링 컨테이너에서는 해당 빈을 관리하지 않는다.

또한 재요청해도 같은 방식으로 진행된다.

 

 

  @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);
    Assertions.assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
    ac.close(); //종료
  }
  @Scope("prototype")
  static class PrototypeBean{
    @PostConstruct
    public void init(){
      System.out.println("PrototypeBean.init");
    }
    @PreDestroy
    public void close(){
      System.out.println("PrototypeBean.close");
    }
  }

해당 코드의 실행 결과에서 close는 나오지 않는다.

이유는 ac.close()는 빈의 관리이지만 프로토타입 빈은 생성 후 관리를 안하기 때문에 나오지 않는 것!

 

정리
  • 프로토타입 빈은 생성, 의존관계 주입, 초기화까지만 처리하고 반환 이후 책임을 지지 않는다. 

 

📝프로토타입 스코프 - 싱글톤 빈과 함께 사용시 문제점

싱글톤 빈에서 프로토타입 빈을 사용하면 문제점이 생긴다. 

싱글톤 빈에서 프로토타입 빈을 사용하면 사용을 할 때마다 새로 생성되지 않는다. 

싱글톤 빈 생성 시점에 한번 생성되고 그 다음부터 내부 참조값으로 가지고 있기 때문이다. 

 

 

프로토타입 빈을 공유하는 문제 
  @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);
  }

프로토타입 빈을 싱글톤 생성 시점에만 주입을 받아 프로토타입 빈도 공유하게 된다. 

이것이 문제이다. 프로토타입 빈의 의의는 사용때마다 새로 생성해서 사용하는 것이다. 

 

 

📝프로토타입 빈, 싱글톤 빈 사용 문제점 해결법

가장 간단한 방법은 싱글톤 빈이 프로토타입을 사용할 대마다 스프링 컨테이너에 새로 요청하는 것이다. 

static class ClientBean {
 @Autowired
 private ApplicationContext ac;
 
 public int logic() {
 	PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
 	prototypeBean.addCount();
 	int count = prototypeBean.getCount();
 	return count;
 }
}
  • 실행해보면 ac.getBean()을 통해서 항상 새로운 프로토타입 빈을 생성하는 것을 볼 수 있다.
  • 의존관계를 외부에서 주입 받는게 아니라 이렇게 직접 필요한 의존 관계를 찾는 것이다. DL 의존관계 조회 
  • 그러나 이렇게 코드를 짜면 스프링 컨테이너에 종속적인 코드가 되고, 단위 테스트도 어려워진다. 
  • 스프링은 이미 해결 방법이 있다.

 

ObjectProvider

지정한 빈을 컨테이너에서 대신 찾아주는 DL 서비스를 제공하는 것이 바로 ObjectProvider이다.

  @Scope("singleton")
  @Component
  static class ClientBean{
    @Autowired
    private ObjectProvider<PrototypeBean> prototypeBeanProvider;
    public int logic() {
      PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
      prototypeBean.addCount();
      int count = prototypeBean.getCount();
      return count;
    }
  }
  • 실행해보면 prototypeBeanProvider.getObject()를 통해 항상 새로운 프로토타입 빈이 생성된다. 
  • 스프링 컨테이너를 통해 해당 빈을 찾아서 반환하는 것이다(DL).
  • 스프링이 제공하는 기능을 사용하지만, 기능이 단순하므로 단위테스트를 만들거나 mock 코드를 만들기 쉽다.
  • 지금 딱 필요한 DL 기능만 제공한다. 

Provider의 추가 기능은 공부하지 않을 것 필요하면 사용(이유 : 별로 사용안하기 때문에)

 

 

📝웹 스코프 

특징

  • 웹 환경에서 동작
  • 프로토타입과 다르게 스프링이 해당 스코프의 종료시점까지 관리한다. 종료 메서드가 호출

종류

  • request : HTTP 요청 하나가 들어고 나갈 때 까지 유지되는 스코프, 각 요청마다 빈 인스턴스 생성되고 관리
  • session : HTTP Session과 동일한 생명주기를 가진다.
  • application : 서블릿 컨텍스트와 동일한 생명주기를 가지는 스코프
  • websocket : 웹 소켓과 동일한 생명주기를 가진다. 

 

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}
    • UUID = 사용자 구분을 위한 ID
    • requestURL 요청한 URL 정보
    • message 사용자의 행위 

Contrlloer

@Controller
@RequiredArgsConstructor
public class LogDemoController {
  private final LogDemoService logDemoService;
  private final MyLogger myLogger;
  @RequestMapping("log-demo")
  @ResponseBody
  public String logDemo(HttpServletRequest request){
    String requestURL = request.getRequestURI().toString();
    myLogger.setRequestURL(requestURL);
    myLogger.log("controller test");
    logDemoService.logic("testId");
    return "OK";
  }
}
  • HttpServletRequest request 를 통해 요청 URL을 받았다.
  • 이렇게 받은 requestURL 값을 myLogger에 저장한다. myLogger의 값은 HTTP 요청 당 각각 구분하는 스코프로 되어있어 걱정 안해도 된다.
  • 컨트롤러에서 controller test라고 로그를 남긴다. 

request

@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);
  }
}
  • 로그를 출력하기 위한 클래스
  • request 스코프로 되어 있어 HTTP 요청을 각각 관리한다. 

Service

@Service
@RequiredArgsConstructor
public class LogDemoService {
  private final MyLogger myLogger;
  public void logic(String id){
    myLogger.log("serviceid = " + id);
  }
}

 

  • 비즈니스 로직이 있는 서비스 계층 

 

  • 해당 방식의 문제점
    • 스프링 애플리케이션을 실행하면 오류가 발생한다.
    • 그 이유는 스프링 애플리케이션 실행 시점에서 싱글톤 빈을 주입하지만 , request 스코프 빈은 사용자 요청에 생성되기 때문이다. 

📝해결방법 - 스코프와 Provider

@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";
 }
}
@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 덕분에 ObjectProvider.getObject()를 호출하는 시점까지 request scope의 빈의 생성을 지연할 수 있다.
  • ObjectProvider.getObject() 를 LogDemoController, LogDemoService에서 각각 한번씩 호출해도 같은 HTTP 요청이면 같은 스프링 빈이 반환된다. -> request 스코프이기 때문이다. 

 

 

ObjectProvider 보완하기 
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyLogger {
}
  •  proxyMode = ScopedProxyMode.TARGET_CLASS 를 추가하자
    • 적용 대상이 인터페이스가 아닌 클래스면 TARGET_CLASS 선택
    • 적용 대상이 인터페이스이면 INTERFACES를 선택
  • 이렇게 하면 MyLogger의 가짜 프록시 클래스를 만들어두고 HTTP request와 상관 없이 가짜 프록시 클래스를 다른 빈에 미리 주입해 둘 수 있다. 
@Controller
@RequiredArgsConstructor
public class LogDemoController {
 private final LogDemoService logDemoService;
 private final MyLogger myLogger;
 
 @RequestMapping("log-demo")
 @ResponseBody
 public String logDemo(HttpServletRequest request) {
 	String requestURL = request.getRequestURL().toString();
 	myLogger.setRequestURL(requestURL);
 	myLogger.log("controller test");
 	logDemoService.logic("testId");
 	return "OK";
 }
}
@Service
@RequiredArgsConstructor
public class LogDemoService {
 private final MyLogger myLogger;
 
 public void logic(String id) {
 	myLogger.log("service id = " + id);
 }
}

 

 

프록시 모드 동작 원리 
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyLogger {
}


System.out.println("myLogger = " + myLogger.getClass());

해당 프록시 모드를 사용해서 myLogger를 출력해보면

myLogger = class hello.core.common.MyLogger$$EnhancerBySpringCGLIB$$b68b726d
  • 완전히 다른 myLogger이 나온 것을 알 수 있다.
    • 이것은 스프링이 CGLIB라는 바이트 라이브러리를 통해 가짜 프록시 객체를 만들어 주입하기 때문이다.
    • 실제 요청이 오면 그때 내부에서 진짜 빈을 요청하는 위임 로직을 통해 정상 실행한다. 
  • 특징
    • 프록시 객체 덕분에 클라이언트는 마치 싱글톤 빈을 사용하듯이 편리하게 request scope를 사용할 수 있다.
    • 사실 Provider를 사용하든, 프록시를 사용하든 핵심 아이디어는 객체 조회를 필요한 시점에 지연처리 하는 것
  • 주의점
    • 이런 특별한 스코프는 꼭 필요한 곳에만 최소화해서 사용하자, 무분별 사용시 유지보수가 어려움 

 

 

✔정리

  • 스코프는 빈이 존재할 수 있는 범위이다. 
  • 프로토 타입 스코프
    • 스코프의 범위는 생성, 의존관계 설정, 초기화까지이다. 
    • 프로토타입 스코프는 매 요청마다 새롭게 생성하여 반환하며 스프링 컨테이너에서 관리를 하지 않는다.
  • 프로토타입과 싱글톤 빈을 같이 사용하면 싱글톤 빈 생성 시점에 한번 생성하여 공유하는 문제점이 생긴다.
    • 이러한 문제점을 해결하기 위해 ObejctProvider을 사용하여 매 요청을 할 수 있다. DL을 하는것 의존관계 탐색 
  • 웹스코프 
    • 웹 환경에서 동작하며 스프링이 해당 스코프의 종료 시점까지 관리한다.
    • request : HTTP 요청 마다 관리를 하며 나갈 때까지 관리를 한다. 
    • 프록시 모드 :  웹 스코프의 생성 시점을 관리하는 것 CGLIB를 사용하여 가짜 스코프를 미리 만들어 오류를 없앤다.