오봉이와 함께하는 개발 블로그

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

BE/Spring

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

오봉봉이 2022. 6. 13. 01:00
728x90

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

프로토타입 스코프의 빈을 요청하면 항상 새로운 객체 인스턴스를 생성해서 반환한다.
하지만, 싱글톤 빈과 함께 사용할 때는 의도한대로 동작하지 않기 때문에 주의해야 한다.

프로토타입 빈 직접 요청

  1. 클라이언트A는 스프링 컨테이너에 프로토타입 빈을 요청
  2. 스프링 컨테이너는 프로토타입 빈을 새로 생성해서 반환(x01). 해당 빈의 count 필드 값은 0이다.
  3. 클라이언트는 조회한 빈에 addCount()를 호출해서 count 필드를 +1 한다.
  4. 결과적으로 프로토타입 빈(x01)의 count는 1이 된다.

  1. 클라이언트B는 스프링 컨테이너에 프로토타입 빈을 요청
  2. 스프링 컨테이너는 프로토타입 빈을 새로 생성해서 반환(x02). 해당 빈의 count 필드 값은 0이다.
  3. 클라이언트는 조회한 빈에 addCount()를 호출해서 count 필드를 +1 한다.
  4. 결과적으로 프로토타입 빈(x02)의 count는 1이 된다.
public class SingletonWithPrototypeTest1 {
    @Test
    void prototypeFind() {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);

        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        prototypeBean1.addCount();
        assertThat(prototypeBean1.getCount()).isEqualTo(1);

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        prototypeBean2.addCount();
        assertThat(prototypeBean2.getCount()).isEqualTo(1);
    }
    @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");
        }
    }
}
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@2fd953a6
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@8dbfffb

각자 다른 스프링 빈을 생성했으며, 테스트 코드도 통과했다.

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

이번에는 clientBean이라는 싱글톤 빈이 의존관계 주입을 통해 프로토타입 빈을 주입받아서 사용한다.

  • clientBean은 싱글톤이기 때문에 보통 스프링 컨테이너 생성 시점에 함께 생성되고, 의존관계 주입도 발생한다.
  1. clientBean은 의존관계 자동 주입을 사용한다. 주입 시점에 스프링 컨테이너에 프로토타입 빈을 요청
  2. 스프링 컨테이너는 프로토타입 빈을 생성해서 clientBean을 반환. 프로토타입 빈의 count 필드 값은 0 이다.
  • 이제 clientBean은 프로토타입 빈을 내부 필드에 보관(정확히는 참조값 보관)

  • 클라이언트A는 clientBean을 스프링 컨테이너에 요청해서 받는다.
    • 싱글톤이므로 항상 같은 clientBean이 반환됨.
  1. 클라이언트A는 clientBean.logic()을 호출
  2. clientBean은 prototypeBeand의 addCount()를 호출해서 프로토타입 빈의 count를 증가시켜 count는 1이 됨.

  • 클라이언트B는 clientBean을 스프링 컨테이너에 요청해서 받는다.
    • 싱글톤이므로 항상 같은 clientBean이 반환됨.
  • 중요한 점은, clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다.
  • 주입 시점에 스프링 컨테이너에 요청해서 생성된 것이지, 사용할 때마다 새로 생성되는 것이 아님.
  1. 클라이언트B는 clientBean.logic()을 호출
  2. clientBean은 prototypeBean의 addCount()를 호출해서 프로토타입 빈의 count를 증가시키는데, 원래 count는 1이었으므로 2가 된다.
public class SingletonWithPrototypeTest1 {
    @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")
//    @RequiredArgsConstructor -> DI 대신에 해도 됨.
    static class ClientBean {
        private final PrototypeBean prototypeBean; // 생성 시점에 이미 주입되어 있어서 계속 같은 것을 사용

        @Autowired // DI
        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");
        }
    }
}

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

개발자의 의도와 다르게 프로토타입 빈이 계속 유지되기 때문에 이럴거면 싱글톤 빈을 사용하지 프로토타입 빈을 사용하는 의미가 없다.

해결방법???

    @Scope("singleton")
//    @RequiredArgsConstructor -> DI 대신에 해도 됨.
    static class ClientBean {
//        private final PrototypeBean prototypeBean; // 생성 시점에 이미 주입되어 있어서 계속 같은 것을 사용

        @Autowired
        ApplicationContext applicationContext;

//        @Autowired // DI
//        public ClientBean(PrototypeBean prototypeBean) {
//            this.prototypeBean = prototypeBean;
//        }
        public int logic() {
            PrototypeBean prototypeBean = applicationContext.getBean(PrototypeBean.class);
            prototypeBean.addCount();
            int count = prototypeBean.getCount();
            return count;
        }
    }

좋은 코드는 아니다.
너무 지저분하고, 스프링에 의존적이기 때문.

참고

여러 빈에서 같은 프로토타입 빈을 주입 받으면 주입 받는 시점에 각각 새로운 프로토타입 빈이 생성됨.

  • clientA -> prototypeBean@x01
  • clientB -> prototypeBean@x02

물론 사용할 때 마다 새로 생성되지는 않는다.

출처 : 인프런 김영한 지식공유자님의 스프링 완전 정복 로드맵 강의
728x90
Comments