🍀spring/스프링 핵심원리 기본

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

pkyung 2023. 2. 11. 20:50
반응형

인프런 김영한님 스프링 핵심 원리 강의를 듣고 정리한 글입니다.

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8/dashboard

 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...

www.inflearn.com

 

 

빈 스코프

 

스프링 빈이 스프링 컨테이너의 시작과 함께 생성되어 스프링 컨테이너가 종료될 때까지 유지된다고 학습했다. 이것은 스프링 빈이 기본적으로 '싱글톤 스코프' 로 생성되기 때문이다. 스코프는 빈이 존재할 수 있는 범위를 뜻한다. 

 

스프링이 지원하는 스코프

- 싱글톤 : 기본 스코프, 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프

- 프로토타입 : 빈 생성과 의존관계 주입까지만 관여하고 그 후는 관리하지 않는 짧은 범위의 스코프

- 웹 관련 스코프

   - request : 웹 요청이 들어오고 나갈 때까지 유지

   - session : 웹 세션이 생성되고 종료될 때까지 유지

   - application : 웹의 서블릿 컨텍스와 같은 범위로 유지

 

 

프로토타입 스코프

 

싱글톤 스코프의 빈을 조회하면 스프링 컨테이너는 항상 같은 인스턴스의 스프링 빈을 반환한다. 반면에 프로토타입 스코프는 스프링 컨테이너에 조회하면 항상 새로운 인스턴스를 생성하여 반환한다. 

 

싱글톤 빈 요청

 

프로토타입 빈 요청

의존관계 주입 이후 관리하지 않는다. 

이후에 또 같은 요청이 와도 새로운 프로토타입 빈을 생성해서 반환한다. 

 

@PreDestroy가 호출되지 않는다. 

 

 

싱글톤 빈은 스프링 컨테이너 생성 시점에 초기화 메서드가 실행되지만 프로토타입 빈은 스프링 컨테이너에서 빈을 조회할 때 생성되고 초기화 메서드도 실행된다.

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);
        Assertions.assertThat(bean1).isNotSameAs(bean2);
        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");
        }
    }
}

프로토타입 빈 특징

- 스프링 컨테이너에게 요청할 때마다 새로 생긴다.

- 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입 그리고 초기화까지만 관여한다. 

- 종료 메서드 호출되지 않는다. => 프로토타입 빈은 조회한 클라이언트가 관리해야 한다.

 

 

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

 

프로토타입 빈은 항상 새로운 객체를 생성해서 반환한다. 하지만 싱글톤 빈과 함께 사용할 때는 의도한 대로 잘 동작하지 않으므로 주의해야한다. 

 

 

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

ClientBean은 생성 시점에 의존관계 주입을 받아 프로토타입 빈을 계속 생성하지 않는다. => 이는 의도한게 아니다. 

public class SingletonWithPrototypeTest1 {

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

        PrototypeBean bean1 = ac.getBean(PrototypeBean.class);
        bean1.addCount();
        Assertions.assertThat(bean1.getCount()).isEqualTo(1);
    }

    @Test
    void singletonClientUsePrototype() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
        ClientBean bean = ac.getBean(ClientBean.class);
        int count1 = bean.logic();
        Assertions.assertThat(count1).isEqualTo(1);

        ClientBean bean1 = ac.getBean(ClientBean.class);
        int count2 = bean1.logic();
        Assertions.assertThat(count2).isEqualTo(2);
    }

    @Scope("singleton")
    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")
    @Getter
    static class PrototypeBean {
        private int count = 0;

        public void addCount() {
            count++;
        }

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

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

싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 계속 유지되는 것이 문제다. 

 

프로토타입 빈을 주입 시점에만 새로 생성하는 것이 아니라 사용할 때마다 새로 생성해서 사용하는 것을 원할 것이다. 

 

 

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

스프링 컨테이너에 요청

 

getBean을 통해 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다. 

외부관계를 외부에서 주입받는게 아니라 이렇게 직접 필요한 의존관계를 찾는 것을 Dependency Lookup(의존관계 조회(탑색)) 이라고 한다. 

=> 이렇게 되면 스프링 컨테이너에 종속적은 코드가 되고 단위테스트가 어려워진다. 

@Autowired
private ApplicationContext ac;

public int logic() {
    PrototypeBean prototypeBean = ac.getBean(PrototypeBean.class);
    prototypeBean.addCount();
    int count = prototypeBean.getCount();
    return count;
}

 

ObjectFactory, ObjectProvider

 

prototypeBeanProvider.getObject()를 통해 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다. 

ObjectProvider의 getObject()를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다.

DL 기능을 제공하는 것

@Scope("singleton")
static class ClientBean {

    @Autowired
    private ObjectProvider<PrototypeBean> prototypeBeanProvider;

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

 

ObjectFactory : 기능이 단순하고 별도의 라이브러리가 필요없고 스프링에 의존적이다. 

ObjectProvider : ObjectFactory의 상속 옵션, 별도의 라이브러리가 필요 없다. 스프링에 의존적이다. 

 

 

JSR-330-Provider

 

 javax.inject.Provider라는 JSR-330 자바 표준을 사용하는 방법이다. 이 방법을 사용하려면 javax.inject:jqvax.inject:1 라이브러리를 gradle에 추가해야한다. 

 

get()메서드 하나로 기능이 매우 단순하다. 자바 표준이므로 다른 컨테이너에서도 사용 가능하다. 

implementation 'org.springframework.boot:spring-boot-starter'
@Scope("singleton")
static class ClientBean {

    @Autowired
    private Provider<PrototypeBean> prototypeBeanProvider;

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

 

언제 프로토타입 빈을 사용할까? 매번 사용할 때마다 의존관계 주입이 완료된 새로운 객체가 필요하면 사용한다.

JSR-330 vs ObjectProvider

: 스프링이 아닌 다른 컨테이너에서 사용할 일이 있다면 JSR-330 ObjectProvider는 DL을 위한 편의 기능을 많이 제공해주고 스프링 외에 별도의 의존관계 추가가 필요 없어서 편리하다. 

 

스프링이 더 다양하고 편리한 기능을 제공해주기 때문에 스프링이 제공하는 기능을 사용하는 방향으로 가자.

 

 

웹 스코프

 

웹스코프는 웹 환경에서만 동작한다.

프로토타입과 다르게 스프링이 해당 스코프의 종료 시점까지 관리한다. => 종료 메서드가 호출된다. 

 

웹 스코프 종류

request : HTTP요청 하나가 들어오고 나갈 때까지 유지되는 스코프, 각각의 http요청마다 별도의 빈 인스턴스가 생성되고 관리된다. 

session : HTTP Session 과 동일한 생명주기를 가지는 스코프

application : 서블릿 컨텍스트와 동일한 생명주기를 가지는 스코프

websocket : 웹 소켓과 동일한 생명주기를 가지는 스코프 

 

 

동시에 요청이 들어와도 별도의 빈 인스턴스가 생성되어 관리된다. 

request 스코프 예제 만들기

 

웹 환경 추가하기

implementation 'org.springframework.boot:spring-boot-starter-web'

이를 추가하면 스프링 부트는 내장 톰켓 서버를 활용해서 웹 서버와 스프링을 함께 실행시킨다. 

웹 라이브러리가 없으면 AnnotationConfigApplicationContext를 기반으로 애플리케이션을 구동한다. 웹 라이브러리가 추가되면 AnnotationConfigWebServerApplicationContext를 기반으로 애플리케이션을 구동한다. 

 

포트 번호 바꾸는 법

application.properties에 server.port = 9090 

 

동시에 여러 HTTP 요청이 오면 정확히 어떤 요청이 남긴 로그인지 구분하기 어렵다. 이럴 떄 사용하는 것이 request  스코프이다. 

 

기대하는 포맷

[UUID][requestURL](message) : UUID를 사용해서 HTTP 요청을 구분한다. 

requestURL 정보도 추가로 넣어 어떤 url 을 요청해서 남은 로그인지 확인한다. 

 

로그 출력을 위한 MyLogger class이다. 

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

컨트롤러

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

서비스

@Service
@RequiredArgsConstructor
public class LogDemoService {

    private final MyLogger myLogger;

    public void logic(String id) {
        myLogger.log("service id = " + id);
    }
}

스프링 애플리케이션을 실행하느 시점에 싱글톤 빈은 빈 생성 후, 주입이 가능하지만 request는 http 요청이 들어올 때 스코프 빈이 생성이 되는데 실제 고객 요청이 없기 때문에 에러가 난다. 

 

스코프와 Provider

 

ObjectProvider를 사용한다. 

해당 빈을 찾아준다. 

private final ObjectProvider<MyLogger> myLoggerProvider;
MyLogger myLogger = myLoggerProvider.getObject();

 

 

스코프와 프록시

 

프록시 방식을 사용한다. 

@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)

 

CGLIB라는 라이브러리로 내 클래스를 상속 받은 가짜 프록시 객체를 만들어 주입한다. 

@Scope와 proxyMode = ScopedProxyMode.TARGET_CLASS) 을 설정하면 스프링 컨테이너는 CGLIB라는 바이트 코드를 조작하는 라이브러리를 사용하여 MyLogger를 상속받은 가짜 프록시 객체를 생성한다. 결과를 확인하면 MyLogger 클래스가 아닌 MyLogger$$EnhancerBySpringCGLIB 라는 클래스로 객체가 만들어진 것을 확인할 수 있다. 

 

의존 관계 주입도 가짜 프록시 객체가 되어있다. 

가짜 프록시 객체는 요청이 오면 그때 내부에서 진짜 빈을 요청하는 위임 로직이 들어있다. 

 

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

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

반응형