Spring

[Spring] Spring 핵심 원리 : 빈 스코프

yjk490 2023. 7. 26. 20:05

빈 스코프란?

빈이 존재할 수 있는 범위이다. 즉, 스프링 빈이 생성되어 소멸되기까지 얼마나 존재할 수 있는지를 의미한다. 스프링 빈은 스프링 컨테이너의 시작과 함께 생성되어 스프링 컨테이너가 종료될 때 소멸된다. 이것은 스프링 빈이 기본적으로 싱글톤 스코프로 생성되기 때문이다. 싱글톤 스코프는 가장 넓은 범위의 스코프다.

스프링이 지원하는 스코프는 다음과 같다.

  • 싱글톤 : 기본 스코프, 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프다.
  • 프로토타입 : 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입까지만 관여하고 더는 관리하지 않는 짧은 범위의 스코프다.
  • 웹 관련 스코프 : 웹 환경에서 동작하는 스코프다. 스프링은 해당 스코프의 종료 시점까지 빈을 관리한다. 스코프 종류에는 request, session, application, websocket이 있다.

빈 스코프는 아래와 같이 지정할 수 있다. 스코프의 기본값은 싱글톤 스코프이므로 @Scope 애노테이션을 붙이지 않으면 당연히 싱글톤 스코프로 지정된다.

// 자동 빈 등록
@Scope("prototype")
@Component
public class HelloBean {}

// 수동 빈 등록
@Scope("prototype")
@Bean
PrototypeBean HelloBean() {
    return new HelloBean();
}

 

프로토타입 스코프

프로토타입 스코프의 빈을 스프링 컨테이너에 조회하면 컨테이너는 항상 새로운 인스턴스를 생성해서 반환한다. 그리고 해당 빈의 생성과 의존관계 주입, 초기화까지만 관여하고 그 이후는 관리하지 않는다. 프로토타입 빈을 관리할 책임은 프로토타입 빈을 반환받은 클라이언트에게 있다. 그래서 @PreDestroy와 같은 소멸 콜백 메서드가 호출되지 않는다.

싱글톤 스코프의 빈은 단 하나의 인스턴스만 생성되고 스프링 컨테이너의 시작과 종료 시점까지 유지, 관리된다는 점과 차이가 있다.

이해를 돕기 위해 싱글톤 스코프와 비교하며 프로토타입 스코프의 빈을 확인해 보자.

// 싱글톤 빈 테스트
public class SingletonTest {
    @Test
    void sigletonBeanFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SingletonBean.class);
        System.out.println("find SingletonBean1");
        SingletonBean bean1 = ac.getBean(SingletonBean.class);
        System.out.println("find SingletonBean2");
        SingletonBean bean2 = ac.getBean(SingletonBean.class);

        System.out.println("bean1 = " + bean1);
        System.out.println("bean2 = " + bean2);
        assertThat(bean1).isSameAs(bean2);

        ac.close();
    }

    @Scope("singleton")
    static class SingletonBean {
        @PostConstruct
        public void init() {
            System.out.println("SingletonBean.init");
        }

        @PreDestroy
        public void close() {
            System.out.println("SingletonBean.close");
        }
    }
}
/* 실행 결과
SingletonBean.init
find SingletonBean1
find SingletonBean2
bean1 = study.componentscan_and_autowired.scope.SingletonTest$SingletonBean@1c93f6e1
bean2 = study.componentscan_and_autowired.scope.SingletonTest$SingletonBean@1c93f6e1
11:50:58.896 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@37d4349f, started on Tue Jul 25 11:50:58 KST 2023
SingletonBean.close
*/

알고 있던 바와 같이 스프링 컨테이너의 시작과 함께 싱글톤 빈이 생성되고 초기화 메서드가 호출된다. 조회된 두 개의 빈은 서로 같은 인스턴스임을 알 수 있고, 소멸 메서드까지 정상적으로 호출되었다. 두 개의 빈이 같은 인스턴스이므로 초기화, 소멸 메서드는 한 번씩만 호출된다.

// 프로토타입 빈 테스트
public class PrototypeTest {
    @Test
    void PrototypeBeanFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        System.out.println("find PrototypeBean1");
        PrototypeBean bean1 = ac.getBean(PrototypeBean.class);
        System.out.println("find PrototypeBean2");
        PrototypeBean bean2 = ac.getBean(PrototypeBean.class);

        System.out.println("bean1 = " + bean1);
        System.out.println("bean2 = " + bean2);
        assertThat(bean1).isNotSameAs(bean2);

        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");
        }
    }
}
/* 실행 결과
find PrototypeBean1
PrototypeBean.init
find PrototypeBean2
PrototypeBean.init
bean1 = study.componentscan_and_autowired.scope.PrototypeTest$PrototypeBean@3adcc812
bean2 = study.componentscan_and_autowired.scope.PrototypeTest$PrototypeBean@35432107
12:06:23.889 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@729d991e, started on Tue Jul 25 12:06:23 KST 2023
*/

싱글톤 빈과는 다르게 스프링 컨테이너가 시작되어도 프로토타입 빈은 생성되지 않는다. 스프링 컨테이너에서 빈을 조회할 때 생성되고 초기화 메서드가 호출된다. 조회된 두 개의 빈은 서로 다른 인스턴스이며 스프링 컨테이너가 종료되더라도 소멸 메서드는 호출되지 않는다. 위에서 말했다시피 프로토타입 스코프의 빈은 초기화 이후로는 스프링 컨테이너에 의해 관리되지 않기 때문이다.

프로토타입 빈의 특징

  • 스프링 컨테이너에 요청할 때마다 새로운 인스턴스가 생성된다.
  • 스프링 컨테이너는 프토토타입 빈의 생성, 의존관계 주입, 초기화까지만 관여한다.
  • 프로토타입 빈의 관리 책임은 클라이언트에게 있다.
  • 그래서 종료 메서드 호출도 클라이언트가 직접 해야 한다.

 

프로토타입 빈을 싱글톤 빈과 함께 사용할 때의 문제점

싱글톤 빈이 의존관계 주입을 통해 프로토타입 빈을 사용하는 경우 프로토타입의 의도대로 동작하지 않는 문제가 있다. 프로토타입 빈이 마치 싱글톤처럼 동작하는 것이다. 프로토타입 빈을 직접 사용하는 경우와 싱글톤 빈 내에서 사용하는 경우를 비교하며 문제점을 알아보자.

프로토타입 빈 직접 사용

public class SingletonWithPrototypeTest {

    @Test
    void prototypeFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);    // 클라이언트 A의 요청
        prototypeBean1.addCount();
        assertThat(prototypeBean1.getCount()).isEqualTo(1);

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);    // 클라이언트 B의 요청
        prototypeBean2.addCount();
        assertThat(prototypeBean2.getCount()).isEqualTo(1);

        ac.close();
    }

    @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.close" + this);
        }
    }
}

PrototypeBean은 count 필드를 갖고 있고 addCount() 메서드를 통해 그 값을 1씩 증가시킨다. 프로토타입 빈의 생성과 동작 과정은 다음과 같다.

  1. 클라이언트 A는 스프링 컨테이너에 PrototypeBean을 요청한다.
  2. 스프링 컨테이너는 요청받은 시점에 빈을 새로 생성해서 반환한다. 이때, 해당 빈의 count 값은 0이다.
  3. 클라이언트는 조회한 빈의 addCount()를 호출하여 count 필드를 1 증가시킨다.
  4. 그 결과 해당 빈의 count 필드 값은 1이 된다.

위 과정을 클라이언트 B의 요청도 똑같이 반복한다. 그러면 결국 PrototypeBean의 인스턴스는 두 개 생성되며 각각의 count 필드 값은 1이 된다.

싱글톤 빈 내에서 프로토타입 빈 사용

public class SingletonWithPrototypeTest {

    @Test
    void singletonClientUsePrototype() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
        ClientBean clientBean1 = ac.getBean(ClientBean.class);    // 클라이언트 A의 요청
        int count1 = clientBean1.logic();
        assertThat(count1).isEqualTo(1);

        ClientBean clientBean2 = ac.getBean(ClientBean.class);    // 클라이언트 B의 요청
        int count2 = clientBean2.logic();
        assertThat(count2).isEqualTo(2);
    }

    @Scope("singleton")
    static class ClientBean {
        private 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.close" + this);
        }
    }
}

ClientBean은 싱글톤 빈이고 의존관계 주입을 통해 PrototypeBean을 사용한다. 즉, PrototypeBean의 주소값을 갖고 있다. 그리고 logic() 메서드를 통해 PrototypeBean의 메서드를 호출하고 PrototypeBean의 필드값을 반환한다. 싱글톤 빈의 생성과 싱글톤 빈이 프토토타입 빈을 사용하는 과정은 다음과 같다.

  1. ClientBean은 싱글톤 빈이므로 스프링 컨테이너의 시작과 함께 생성되고 의존관계 주입이 발생한다.
  2. ClientBean의 의존관계 주입 과정에서 스프링 컨테이너는 프로토타입 빈을 생성해서 ClientBean에게 반환한다.
  3. ClientBean은 프로토타입 빈의 참조값을 내부 필드에 보관한다.
  4. 클라이언트 A는 스프링 컨테이너에 ClientBean을 요청하고 반환받는다.
  5. 클라이언트 A는 ClientBean의 logic()을 호출한다.
  6. ClientBean은 PrototypeBean의 addCount()를 호출해서 prototypeBean의 count 필드 값을 1 증가시킨다. (count=1)
  7. 클라이언트 B는 스프링 컨테이너에 ClientBean을 요청하고 반환받는다. 이때, ClientBean은 싱글톤 빈이므로 항상 같은 ClientBean이 반환된다.
  8. ClientBean이 내부에 갖고 있는 PrototypeBean은 이미 과거에 주입이 끝난 빈이다. 주입 시점에 스프링 컨테이너에 요청해서 프로토타입 빈이 생성된 것이지, 클라이언트가 ClientBean을 요청할 때마다 새로 생성되는 것이 아니다.
  9. 클라이언트 B는 ClientBean의 logic()을 호출한다.
  10. ClientBean은 PrototypeBean의 addCount()를 호출해서 prototypeBean의 count 필드 값을 1 증가시킨다. (count=2)

프로토타입 스코프의 기능에 따르면 해당 스코프로 지정된 빈은 요청될 때마다 새로운 인스턴스가 생성된다. 그러나 지금 상황은 마치 싱글톤 스코프처럼 동작한다. 싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에 프로토타입 빈이 새로 생성되기는 하지만 싱글톤과 함께 유지되기 때문이다.

이것은 프로토타입 스코프의 사용 목적에 맞지 않다. 프로토타입 빈을 주입 시점에만 새로 생성하는 것이 아니라 사용할 때마다 새로 생성되도록 하는 것이 본래 목적에 맞다. 이 문제를 의존관계 탐색(DL, Dependency Lookup)을 통해 해결한다.

 

의존관계 탐색(DL, Dependency Lookup)

싱글톤 빈이 의존하는 프로토타입 빈을 항상 새로운 인스턴스로 사용하기 위해서는 프로토타입 빈을 사용할 때마다 스프링 컨테이너에 요청하면 된다. 이처럼 의존관계를 외부에서 주입(DI) 받는 것이 아니라 직접 필요한 의존객체를 찾는 것을 의존관계 탐색(DL)이라고 한다. 코드를 통해 확인해 보자.

    @Scope("singleton")
    static class ClientBean {
        private ApplicationContext ac;

        @Autowired
        public ClientBean(ApplicationContext ac) {
            this.ac = ac;
        }

        public int logic() {
            PrototypeBean prototypeBean = prototypeBeanProvider.get();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

그러나 이런 식으로 스프링의 ApplicationContext 전체를 주입받게 되면 스프링 컨테이너에 종속적인 코드가 되고 단위 테스트가 어려워진다. 지금 필요한 기능은 지정한 프로토타입 빈을 컨테이너에서 찾아주기만 하는 DL정도의 기능만 제공하는 무언가가 있으면 된다. 그러한 역할을 수행하는 클래스가 있다. 스프링이 제공하는 ObjectProvider와 Java 표준인 JSR-330 Provider이다.

ObjectProvider

ObjectProvider는 지정한 빈을 컨테이너에서 대신 찾아주는 DL 서비스를 제공하는 클래스다. 과거에는 ObjectFactory가 있었는데 여기에 편의 기능을 추가해서 만들어진 것이 ObjectProvider이다. 둘 다 스프링에 있는 클래스다.

    @Scope("singleton")
    static class ClientBean {
        private ObjectProvider<PrototypeBean> prototypeBeanProvider;

        @Autowired
        public ClientBean(ObjectProvider<PrototypeBean> prototypeBeanProvider) {
            this.prototypeBeanProvider = prototypeBeanProvider;
        }

        public int logic() {
            PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

테스트를 실행해 보면 prototypeBeanProvider.getObject()을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 알 수 있다. ObjectProvider의 getObject()를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. 스프링이 제공하는 클래스지만 기능이 단순하므로 단위테스트를 만들기 쉽다. 또한 라이브러리를 따로 추가할 필요가 없다.

Provider

Provider도 마찬가지로 DL 기능을 제공하는 클래스다. 그러나 ObjectProvider와는 다르게 Java에서 제공하는 클래스다. javax.inject.Provider라는 JSR-330 자바 표준이다. 이 방법을 사용하려면 Gradle에 라이브러리를 추가해야 한다.

Spring boot 3.0 미만 : javax.inject:javax.inject:1
Spring boot 3.0 이상 : jakarta.inject:jakarta.inject-api:2.0.1

    @Scope("singleton")
    static class ClientBean {
        private Provider<PrototypeBean> prototypeBeanProvider;

        @Autowired
        public ClientBean(Provider<PrototypeBean> prototypeBeanProvider) {
            this.prototypeBeanProvider = prototypeBeanProvider;
        }

        public int logic() {
            PrototypeBean prototypeBean = prototypeBeanProvider.get();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

Provider의 get()을 통해 항상 새로운 프로토타입 빈을 반환받는다. ObjectProvider의 getObject()와 마찬가지로 Provider의 get()을 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. Java 표준이므로 스프링이 아닌 다른 컨테이너에서도 사용이 가능하며 기능이 단순하여 단위테스트를 만들기 쉽다. 그러나 별도의 라이브러리를 추가해야 한다.

 

웹 스코프

웹 스코프는 웹 환경에서 동작하는 스코프다. 프로토타입 스코프와는 다르게 스프링이 해당 스코프의 종료 시점까지 관리한다. 즉, 조건에 따라 종료 메서드가 호출된다. 웹 스코프의 종류는 다음과 같다.

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

위 스코프들은 범위만 다르고 동작 방식은 비슷하다. 그래서 이 글에서는 request 스코프에 대해서만 다뤄본다.

Request 스코프 사용 예제

시작하기에 앞서 우선 다음과 같은 웹 라이브러리를 Gradle에 추가해야 한다. 웹 스코프는 웹 환경에서만 동작하기 때문이다. 'org.springframework.boot:spring-boot-starter-web'

동시에 여러 HTTP 요청이 왔을 때 HTTP 요청별로 로그를 구분하기 위해 request 스코프를 사용하는 예제를 만든다. 다음 예시와 같이 로그가 남도록 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 destroy
  • 포맷 : [UUID] [requestURL] {message}
  • UUID를 사용해서 HTTP 요청을 구분한다.
  • requestURL 정보도 추가하여 어떤 URL을 요청해서 남은 로그인지 확인한다.

MyLogger

@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 destroy : " + this);
    }
}
  • 로그를 출력하기 위한 MyLogger 클래스다.
  • request 스코프로 지정되어 있기 때문에 이 빈은 HTTP 요청마다 하나씩 생성되고 HTTP 요청이 끝나는 시점에 소멸된다.
  • 이 빈이 생성되는 시점 즉, HTTP 요청이 들어오는 시점에 @PostConstruct가 붙은 초기화 메서드가 호출되어 UUID를 생성하고 필드에 저장한다.
  • 이 빈이 소멸되는 시점 즉, HTTP 요청이 종료되는 시점에 @PreDestroy가 붙은 종료 메서드가 호출되어 종료 메세지를 남기고 빈이 소멸된다.
  • requestURL은 이 빈이 생성되는 시점에는 알 수 없으므로 외부에서 setter메서드를 통해 입력받는다.
  • request 스코프의 빈이 HTTP 요청 시에 생성되는 것은 맞지만 request 정보를 받고 나서 생성되는 것은 아니므로 빈 생성 시점에 requestURL을 알 수없다.

LogDemoController

@Controller
public class LogDemoController {
    private final LogDemoService logDemoService;
    private final MyLogger myLogger;

    @Autowired
    public LogDemoController(LogDemoService logDemoService, MyLogger myLogger) {
        this.logDemoService = logDemoService;
        this.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 " + myLogger.toString();
    }
}
  • MyLogger가 잘 작동하는지 확인하는 테스트용 컨트롤러다.
  • requestURL 값 : http://localhost:8080/log-demo
  • requestURL 값을 myLogger에 저장한다. myLogger는 HTTP 요청마다 한 개씩 생성되고 UUID로 구분되므로 값이 섞이지 않는다.
  • 컨트롤러에서 Controller test라는 로그를 남긴다.
  • HTTP 요청마다 MyLogger가 생성되는지 확인하기 위해 페이지에 해당 인스턴스의 정보를 출력한다.

LogDemoService

@Service
public class LogDemoService {
    private final MyLogger myLogger;

    @Autowired
    public LogDemoService(MyLogger myLogger) {
        this.myLogger = myLogger;
    }

    public void logic(String testId) {
        myLogger.log("Service id = " + testId);
    }
}
  • MyLogger가 잘 작동하는지 확인하는 테스트용 서비스 클래스다.
  • requestURL과 같은 웹 관련 정보가 서비스 계층까지 넘어가는 것은 유지보수 관점에서 적절하지 않다. 서비스 계층이 웹 기술에 종속되기 때문이다. 웹과 관련된 부분은 컨트롤러까지만 사용해야 한다.
  • request 스코프의 MyLogger 덕분에 requestURL 파라미터로 넘기지 않고, MyLogger의 멤버변수에 저장해서 서비스 계층을 깔끔하게 유지할 수 있다.

실행 결과

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;

스프링 애플리케이션을 실행하면 위와 같은 에러가 발생한다. 애플리케이션이 시작되는 시점에는 스프링 컨테이너가 싱글톤 빈을 생성하고 의존관계 주입을 하는 것이 가능하지만, request 스코프 빈은 HTTP 요청이 들어와야 생성되기 때문이다.

즉, 컨트롤러와 서비스는 MyLogger를 의존하는데 두 클래스가 의존관계 주입을 받는 시점에는 MyLogger가 아직 생성되지 않았기 때문에 에러가 발생한다. MyLogger는 실제 HTTP 요청이 들어와야 생성된다. 따라서 MyLogger의 생성을 HTTP 요청 시점까지 지연시켜야 이를 해결할 수 있다. 그 방법에는 ObjectProvider와 프록시가 있다.

해결 방법 1 - ObjectProvider

MyLogger를 바로 의존관계 주입받아 사용하는 것이 아니라 ObjectProvider를 사용해서 스프링 컨테이너로부터 조회하여 사용하면 된다.

public class LogDemoController {
    private final LogDemoService logDemoService;
    private final ObjectProvider<MyLogger> myLoggerProvider;

    @Autowired
    public LogDemoController(LogDemoService logDemoService, ObjectProvider<MyLogger> myLoggerProvider) {
        this.logDemoService = logDemoService;
        this.myLoggerProvider = 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-A");

        return "OK " + myLogger.toString();
    }
}

@Service
public class LogDemoService {
    private final ObjectProvider<MyLogger> myLoggerProvider;

    @Autowired
    public LogDemoService(ObjectProvider<MyLogger> myLoggerProvider) {
        this.myLoggerProvider = myLoggerProvider;
    }

    public void logic(String testId) {
        MyLogger myLogger = myLoggerProvider.getObject();
        myLogger.log("Service id = " + testId);
    }
}
  • ObjectProvider의 getObject()를 호출하는 시점까지 request 스코프 빈의 생성을 지연시킬 수 있다.
  • objectProvider.getObject()를 호출하는 시점에는 HTTP 요청이 진행 중이므로 MyLogger의 생성이 정상 처리된다.
  • request 스코프의 빈은 HTTP 요청 당 한 개씩 생성되므로 LogDemoController와 LogDemoService에서 조회한 MyLogger는 모두 같은 인스턴스이다.

스프링 애플리케이션을 실행하고 브라우저에 http://localhost:8080/log-demo를 요청하면 최초 요구사항과 같이 로그가 출력됨을 확인할 수 있다. 두 번 요청했으므로 두 개의 UUID를 볼 수 있다. MyLogger 인스턴스 또한 두 개가(MyLogger@56513f17, MyLogger@72828efa)가 생성되었다.

[93cd34fe-9a08-40c4-a34b-8afd29cbcfff] request scope bean create : study.componentscan_and_autowired.common.MyLogger@56513f17
[93cd34fe-9a08-40c4-a34b-8afd29cbcfff] [http://localhost:8080/log-demo] Controller test
[93cd34fe-9a08-40c4-a34b-8afd29cbcfff] [http://localhost:8080/log-demo] Service id = testId-A
[93cd34fe-9a08-40c4-a34b-8afd29cbcfff] request scope bean destroy : study.componentscan_and_autowired.common.MyLogger@56513f17
[52b372a7-a259-4383-a6bd-c3bdf1242881] request scope bean create : study.componentscan_and_autowired.common.MyLogger@72828efa
[52b372a7-a259-4383-a6bd-c3bdf1242881] [http://localhost:8080/log-demo] Controller test
[52b372a7-a259-4383-a6bd-c3bdf1242881] [http://localhost:8080/log-demo] Service id = testId-A
[52b372a7-a259-4383-a6bd-c3bdf1242881] request scope bean destroy : study.componentscan_and_autowired.common.MyLogger@72828efa

그런데 request 스코프 빈은 HTTP 요청이 들어올 때 생성된다고 했는데 objectProvider.getObject()를 통해 빈의 생성을 지연시킨다는 말은 조금 이해하기 힘들다. HTTP 요청이 아니라 빈을 조회할 때 생성되는, 프로토타입 스코프와 비슷하게 작동한다는 설명처럼 들린다. 빈의 생성을 지연시키는 것은 request 스코프의 동작 방식과 ObjectProvider의 특성을 조합한 결과다.

보다 정확히 말하면 request 스코프는 active 속성을 갖고 있는데 이것은 빈이 HTTP 요청을 처리하는 동안만 활성화되도록 설정하는 기능을 제공한다. 빈이 활성 상태라는 것은 HTTP 요청이 들어왔을 때 빈을 '생성할 수 있는 상태'가 되었다는 것을 의미한다. 그리고 ObjectProvider를 통해 빈을 조회할 때, 빈이 존재하지 않으면 그 빈을 생성해서 반환한다.

그래서 request 스코프 빈이 활성 상태 즉, HTTP 요청이 들어온 상태라면 ObjectProvider로 빈을 조회하거나 @Autowired로 주입받을 때 해당 빈은 자동으로 생성된다.

active 속성의 기본값은 true이기 때문에 따로 설정하지 않으면 활성 상태로 동작한다. 만약 active 속성을 false로 지정하면 빈은 수동으로 생성해야 한다.

해결 방법 2 - 프록시

우선 프록시의 사전적 의미는 '대리인' 혹은 '대리자'이다. 그래서 프록시 객체는 원래의 객체에 대한 대리 객체로서 동작하며, 해당 객체에 대한 접근을 중간에서 제어하고 조작할 수 있게 해 준다.

proxyMode 속성을 추가하면 MyLogger에 대한 프록시 객체를 사용하여 스프링 컨테이너의 시작 시점에 의존관계 주입을 하고 실제 HTTP 요청이 오면 그때 진짜 MyLogger 객체를 생성한다.

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyLogger { ··· }
  • @Scope에 proxyMode 속성을 추가한다.
  • 적용 대상이 클래스면 ScopedProxyMode.TARGET\_CLASS를 선택한다.
  • 적용 대상이 인터페이스면 ScopedProxyMode.INTERFACES를 선택한다.
  • 이 설정을 적용하면 MyLogger의 가짜 프록시 클래스를 만들어 두고 HTTP 요청과 상관없이 가짜 프록시 클래스를 다른 빈에 미리 주입해 둘 수 있다.

그리고 LogDemoController와 LogDemoService 클래스를 ObjectProvider를 사용하기 전 코드로 되돌려 놓고 실행해 보면 정상 작동함을 확인할 수 있다. 그리고 가짜 프록시 객체의 클래스 정보를 출력해보면 다음과 같다.

myLogger = class study.componentscan_and_autowired.common.MyLogger$$EnhancerBySpringCGLIB$$1e1f2bcf
[ec939767-97a9-49df-bb70-598ed3a0fda4] request scope bean create : study.componentscan_and_autowired.common.MyLogger@56e995ef
[ec939767-97a9-49df-bb70-598ed3a0fda4] [http://localhost:8080/log-demo] Controller test
[ec939767-97a9-49df-bb70-598ed3a0fda4] [http://localhost:8080/log-demo] Service id = testId-A
[ec939767-97a9-49df-bb70-598ed3a0fda4] request scope bean destroy : study.componentscan_and_autowired.common.MyLogger@56e995ef

@Scope의 proxyMode = ScopedProxyMode.TARGET\_CLASS)를 설정하면 스프링 컨테이너는 CGLIB이라는 바이트코드 조작 라이브러리를 사용해서 MyLogger를 상속받은 가짜 프록시 객체를 생성해서 등록한다. 위 결과에서 볼 수 있듯이 순수한 MyLogger 클래스가 아니라 MyLogger$$EnhancerBySpringCGLIB$$1e1f2 bcf라는 클래스로 만들어진 객체가 대신 주입된 것을 확인할 수 있다.

가짜 프록시 객체는 요청이 오면 그때 내부에서 진짜 빈을 요청하는 위임 로직이 들어있다. 그래서 클라이언트가 MyLogger의 logic() 메서드를 호출하면 사실은 가짜 프록시 객체의 메서드를 호출한 것이다. 그 후, 가짜 프록시 객체는 진짜 MyLogger의 logic() 메서드를 호출한다. 가짜 프록시 객체는 request 스코프와는 관계가 없다. 싱글톤 빈처럼 동작하며 내부에 위임 로직이 있을 뿐이다.

가짜 프록시 객체는 원본 클래스를 상속받아 만들어졌기 때문에 이 객체를 사용하는 클라이언트 입장에서는 원본인지 가짜 프록시 객체인지 모르고 동일하게 사용할 수 있다. 클라이언트는 마치 싱글톤 빈을 사용하듯 편리하게 request 스코프의 빈을 사용하면 된다.

단지 애노테이션의 설정 변경만으로도 원본 객체를 프록시 객체로 대체할 수 있다. 이것이 다형성과 DI컨테이너가 갖는 장점이다.