본문 바로가기
spring

Bean Scope빈스코프

by 김선지 2024. 6. 2.

1. 싱글톤 스코프

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

 

2. 프로토타입 스코프

 - 빈을 조회하면 스프링 컨테이너는 항상 새로운 인스턴스를 생성하고 필요한 의존관계를 주입하여 초기화하고 반환한다. 이후 클라이언트에게 제공하고 더이상 관리하지 않는다. 빈을 관리할 책임은 클라이언트에게 있다.

 고로 @PreDestroy같은 종료 메서드가 호출되지 않는다.

 

싱글톤 안에서 프로토타입 빈 사용하는 경우 (프로토타입 스코프를 싱글톤 빈과 함께 사용할 시)

 - 싱글톤 안의 프로토타입 빈은 이미 DI가 끝났기 때문에 안의 디펜던시가 프로토타입 빈이라고 해도 새로운 프로토타입 빈이 만들어지지 않는다.

이를 해결하기 위해 ObjectProvider 클래스를 이용한다. 해당 클래스는 지정한 빈을 컨테이너에서 대신 찾아주는 DL(디펜던시 룩업)서비스를 제공해준다.

 

하지만 스프링에 의존적이기 때문에 JSR-330이 나왔다. (자바 표준) - jakarta.inject.Provider

(단순하다, 별도의 라이브러리가 필요하다, 자바표준이므로 스프링이 아닌 다른 컨테이너에서도 적용 가능)

import jakarta.inject.Provider;
package hello.core.scope;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;

public class SingletonWihtPrototypeTest1 {

    @Test
    void prototyeFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean1.addCount();
        prototypeBean2.addCount();
        Assertions.assertThat(prototypeBean2.getCount()).isEqualTo(1);

    }

    @Test
    void prototypeBeanInSingleton() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
        ClientBean bean1 = ac.getBean(ClientBean.class);
        ClientBean bean2 = ac.getBean(ClientBean.class);
        bean1.logic();
        int bean2Count = bean2.logic();
        Assertions.assertThat(bean2Count).isEqualTo(1);
    }
    @Scope("singleton")
    static class ClientBean {

        @Autowired
        private ObjectProvider<PrototypeBean> prototypeBeanProvider;
        // ObjectProvider

        public int logic() {
            PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }
    @Scope("prototype")
    static class PrototypeBean {
        private int count = 0;

        public void addCount() {
            this.count++;
        }

        public int getCount() {
            return this.count;
        }

        @PostConstruct
        public void init() {
            System.out.println("PrototypeBean.init " + this);
        }

        @PreDestroy
        public void destroy() {
            System.out.println("PrototypeBean.destroy" + this);
        }
    }
}

 

 

 

3. 웹 스코프

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

 

웹스코프 종류

request HTTP 요청 하나가 들어오고 나갈 때까지 유지되는 스코프로 각각의 HTTP요청마다 별도의 빈 인스턴스가 생성되고 관리됨
(한 클라이언트 전용으로 빈이 만들어짐)
session HTTP Session과 동일한 생명주기를 가지는 스코프
application 서블릿 컨텍스트와 동일한 생명주기를 가지는 스코프
websocket 웹소켓과 동일한 생명주기를 가지는 스코프

 

다만 빈 자체가 요청이 들어와야만 생성되기 때문에 바로 DI를 해줄 수 없기 때문에 ObjectProvider같은 DL을 활용해야한다.

또는 프록시를 이용한다.

프록시를 이용하면 CGLIB이라는 바이트 코드를 조작하는 라이브러리를 이용해서 MyLogger의 가짜 프록시 클래스를 만들어두고 HTTP request와 상관 없이 가짜 프록시 클래스를 다른 빈에 미리 주입해둘 수 있다.

이후 실제 호출하는 시점에 진짜 MyLogger를 찾아서 동작한다.

 

즉, 프록시 객체 덕분에 클라이언트는 싱글톤 빈을 사용하듯 편리하게 request scope를 사용할 수 있다.

핵심 아이디어는 진짜 객체 조회를 꼭 필요한 시점까지 지연처리 한다는 점이다.

 

컨트롤러

package hello.core.web;

import hello.core.common.MyLogger;
import jakarta.servlet.http.HttpServletRequest;
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;

@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";
    }
}

 

 

MyLogger

// proxyMode 속성을 이용한다. 적용되는 속성이 클래스기 때문에 TARGET_CLASS

package hello.core.common;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
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 created:" + this);
    }

    @PreDestroy
    public void close() {
        System.out.println("[" + uuid + "]" + "request scope bean close:" + this);
    }
}

'spring' 카테고리의 다른 글

Exception handling  (0) 2024.06.24
spring MVC  (0) 2024.06.15
에디터 글 DB 저장, 이미지 base 64인코딩 데이터 DB저장  (0) 2024.05.29
@AutoConfig, @ComponentScan, @Autowired, Filter  (0) 2024.05.28
Spring Container의 생성 과정  (0) 2024.05.23