[Spring Boot][2] 9-1. 빈 스코프

sorzzzzy·2021년 8월 29일
0

Spring Boot - RoadMap 1

목록 보기
14/46
post-thumbnail

🏷 빈 스코프란?

지금까지 우리는 스프링 빈이 스프링 컨테이너의 시작과 함께 생성되어서, 스프링 컨테이너가 종료될 때 까지 유지된다고 배웠다!
이것은 스프링 빈이 기본적으로 싱글톤 스코프로 생성되기 때문이다.
스코프는 번역 그대로 빈이 존재할 수 있는 범위를 뜻함

스프링은 다음과 같은 다양한 스코프를 지원한다❗️

  • 싱글톤 : 기본 스코프, 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프. 가장 생명주기가 길다!
  • 프로토타입 : 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입까지만 관여하고 더는 관리하지 않는 매우 짧은 범위의 스코프.
  • 웹 관련 스코프 : 스프링 웹과 관련된 기능이 들어가야 쓸 수 있는 스코프.
    • request : 웹 요청이 들어오고 나갈때 까지 유지되는 스코프.
    • session : 웹 세션이 생성되고 종료될 때 까지 유지되는 스코프.
    • application : 웹의 서블릿 컨텍스트와 같은 범위로 유지되는 스코프.

✔️ 빈 스코프 지정 방법
1️⃣ 컴포넌트 스캔 자동 등록

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

2️⃣ 수동 등록

@Scope("prototype")
  @Bean
  PrototypeBean HelloBean() {
      return new HelloBean();
  }

💡 지금까지는 계속 싱글톤 스코프만 사용했으니, 싱글톤이랑 비교하면서 하나하나 알아보도록 하자 !



🏷 프로토타입 스코프

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

✔️ 싱글톤 빈 요청

1️⃣ 싱글톤 스코프의 빈을 스프링 컨테이너에 요청한다.
2️⃣ 스프링 컨테이너는 본인이 관리하는 스프링 빈을 반환한다.
3️⃣ 이후에 스프링 컨테이너에 같은 요청이 와도 같은 객체 인스턴스의 스프링 빈을 반환한다.

✔️ 프로토타입 빈 요청 1

1️⃣ 프로토타입 스코프의 빈을 스프링 컨테이너에 요청한다.
2️⃣ 스프링 컨테이너는 이 시점에 프로토타입 빈을 생성하고, 필요한 의존관계를 주입한다.

✔️ 프로토타입 빈 요청 2

3️⃣ 스프링 컨테이너는 생성한 프로토타입 빈을 클라이언트에 반환한다.
4️⃣ 이후에 스프링 컨테이너에 같은 요청이 오면 항상 새로운 프로토타입 빈을 생성해서 반환한다.

✔️ 정리

  • 핵심은 스프링 컨테이너는 프로토타입 빈을 생성하고, 의존관계 주입, 초기화까지만 처리한다는 것이다.
  • 클라이언트에 빈을 반환하고, 이후 스프링 컨테이너는 생성된 프로토타입 빈을 관리하지 않는다.
  • 프로토타입 빈을 관리할 책임은 프로토타입 빈을 받은 클라이언트에 있다.
    그래서 @PreDestroy 같은 종료 메서드가 호출되지 않는다.

test/../scope/SingletonTest.java 생성 후 싱글톤 테스트

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 SingletonTest {
    @Test
    public 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");
        }
    }
}

⬆️ 실행 결과

test/../scope/SingletonTest.java 생성 후 프로토타입 테스트

package hello.core.scope;
import org.junit.jupiter.api.Test;
import
        org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import static org.assertj.core.api.Assertions.*;

public class PrototypeTest {

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

⬆️ 실행 결과


❗️ 프로토타입 빈의 특징 정리

  • 스프링 컨테이너에 요청할 때마다 새로 생성된다.
  • 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입 그리고 초기화까지만 관여한다.
  • 종료 메서드가 호출되지 않는다.
  • 그래서 프로토타입 빈은 프로토타입 빈을 조회한 클라이언트가 관리해야 한다.
    종료 메서드에 대한 호출도 클라이언트가 직접 해야한다.


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

스프링 컨테이너에 프토토타입 스코프의 빈을 요청하면 항상 새로운 객체 인스턴스를 생성해서 반환한다.
하지만❗️ 싱글톤 빈과 함께 사용할 때 문제가 발생할 수 있다❗️


⬆️ 두 개의 빈을 요청한 후 결과가 2가아닌 1 ❓


싱글톤 빈에서 프로토타입 빈을 사용하는 예제를 보자!

✔️ 싱글톤에서 프로토타입 빈 사용
clientBean 은 싱글톤이므로, 보통 스프링 컨테이너 생성 시점에 함께 생성되고, 의존관계 주입도 발생한다.
1️⃣ clientBean 은 의존관계 자동 주입을 사용한다. 주입 시점에 스프링 컨테이너에 프로토타입 빈을 요청한다.
2️⃣ 스프링 컨테이너는 프로토타입 빈을 생성해서 clientBean 에 반환한다. 프로토타입 빈의 count 필드 값은 0이다.
이제 clientBean 은 프로토타입 빈을 내부 필드에 보관한다. (정확히는 참조값을 보관한다.)
클라이언트 A는 clientBean 을 스프링 컨테이너에 요청해서 받는다.
싱글톤이므로 항상 같은 clientBean 이 반환된다.
3️⃣ 클라이언트 A는 clientBean.logic() 을 호출한다.
4️⃣ clientBeanprototypeBeanaddCount() 를 호출해서 프로토타입 빈의 count를 증가한다. count값이 1이 된다.
클라이언트 B는 clientBean 을 스프링 컨테이너에 요청해서 받는다.
싱글톤이므로 항상 같은 clientBean 이 반환된다.
여기서 중요한 점이 있는데, clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다.
주입 시점에 스프링 컨테이너에 요청해서 프로토타입 빈이 새로 생성이 된 것이지, 사용 할 때마다 새로 생성되는 것이 아니다!

5️⃣ 클라이언트 B는 clientBean.logic() 을 호출한다.
6️⃣ clientBean 은 prototypeBeanaddCount() 를 호출해서 프로토타입 빈의 count를 증가한다. 원래 count 값이 1이었으므로 2가 된다!

test/../scope/SingletonWithPrototypeTest1 생성

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.assertThat;

public class SingletonWithPrototypeTest1 {

    @Test
    void prototypeFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        prototypeBean1.addCount();
        // addCount 한 이후이므로 값은 1이 되어야 함
        assertThat(prototypeBean1.getCount()).isEqualTo(1);
        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        // 마찬가지로 addCount 한 이후이므로 값은 1이 되어야 함
        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();
        assertThat(count1).isEqualTo(1);
        ClientBean clientBean2 = ac.getBean(ClientBean.class);
        int count2 = clientBean2.logic();
        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")
    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");
        }
    }
}

⬆️ 스프링은 일반적으로 싱글톤 빈을 사용하므로, 싱글톤 빈이 프로토타입 빈을 사용하게 된다.
그런데 싱글톤 빈은 생성 시점에만 의존관계 주입을 받기 때문에, 프로토타입 빈이 새로 생성되기는 하지만, 싱글톤 빈과 함께 계속 유지되는 것이 문제가 된다😂

우리가 원하는 것은 프로토타입 빈을 주입 시점에만 새로 생성하는 것이 아니고, 사용할 때 마다 새로 생성해서 사용하는 것 이다❗️



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

싱글톤 빈과 프로토타입 빈을 함께 사용할 때, 어떻게 하면 사용할 때 마다 항상 새로운 프로토타입 빈을 생성할 수 있을까🤷🏻‍♀️?


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;
	} 
}
  • 실행해보면 ac.getBean() 을 통해 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다!
  • 그런데 이렇게 스프링의 애플리케이션 컨텍스트 전체를 주입받게 되면, 스프링 컨테이너에 종속적인 코드가 되고, 단위 테스트도 어려워진다🤔
  • 지금 필요한 기능은 지정한 프로토타입 빈을 컨테이너에서 대신 찾아주는 딱! DL 정도의 기능만 제공하는 무언가가 있으면 된다!

그리고 이 방법은 조금..ㅎ 무식한 방법..!이다..!

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


2️⃣ ObjectFactory, ObjectProvider

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

@Autowired
  private ObjectProvider<PrototypeBean> prototypeBeanProvider;
  public int logic() {
      PrototypeBean prototypeBean = prototypeBeanProvider.getObject();
      prototypeBean.addCount();
      int count = prototypeBean.getCount();
      return count;
}
  • 실행해보면 prototypeBeanProvider.getObject() 을 통해 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다!
  • ObjectProvidergetObject() 를 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. (DL 기능 완료^_^)
  • ObjectProvider 는 지금 딱 필요한 DL 정도의 기능만 제공한다!

3️⃣ JSR-330 Provider

마지막 방법은 javax.inject.Provider 라는 JSR-330 자바 표준을 사용하는 방법이다.

📌 javax.inject:javax.inject:1 라이브러리를 gradle에 추가해야 한다!

@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;
        }
    }
  • 실행해보면 provider.get() 을 통해서 항상 새로운 프로토타입 빈이 생성되는 것을 확인할 수 있다!
  • provider 의 get() 을 호출하면 내부에서는 스프링 컨테이너를 통해 해당 빈을 찾아서 반환한다. (이것도 DL 기능 possible^_^)
  • Provider 또한 딱! 필요한! DL 정도의 기능만! 제공한다!
  • get() 메서드 하나로 기능이 매우 단순하다.
  • 그러나 살짝 귀찮은 점은 ! 별도의 라이브러리가 필요하다.
  • 자바 표준이므로 스프링이 아닌 다른 컨테이너에서도 사용할 수 있다.

✔️ 정리

그러면 프로토타입 빈을 언제 사용할까🤔?
➡️ 매번 사용할 때 마다 의존관계 주입이 완료된 새로운 객체가 필요할 때 사용하면 된다!
(그런데 실무에서 웹 애플리케이션을 개발해보면, 싱글톤 빈으로 대부분의 문제를 해결할 수 있기 때문에 프로토타입 빈을 직접적으로 사용하는 일은 매우 드물다)
ObjectProvider , JSR330 Provider 등은 프로토타입 뿐만 아니라 DL이 필요한 경우는 언제든지 사용할 수 있다.




길어지니,,2탄으로,,,^^!

profile
Backend Developer

0개의 댓글