Backend/Spring

[스프링핵심원리 - 기본편]프로토타입 스코프 - 싱글톤 빈과 함께 사용시 문제점

seung_soos 2023. 3. 31. 21:30

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

프로토타입 빈 직접요청

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

Test

public class SingletonWithPrototypeTest1 {

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

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

    }

    @Scope("prototype")
    static class PrototypeBean{
        private int count;
        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");
        }
    }
}

 

결과

 

21:39:22.329 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6c80d78a
21:39:22.359 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
21:39:22.404 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
21:39:22.407 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
21:39:22.408 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
21:39:22.410 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@4d14b6c2
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@6950ed69

Process finished with exit code 0

 

▶ 프로토타입빈의 당연한결과이다.

 

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

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

1. clientBean은 싱글톤이므로, 보통 스프링 컨테이너 생성시점에 함께 생성되고, 의존관계 주입도 받는다.

2. clientBean은 의존관계 자동 주입을 사용한다. 주입시점에 스프링 컨테이너에 프로토타입 빈을 요청한다.

3. 스프링 컨테이너는 프로토타입 빈을 생성해서 clientBean에 반환한다. 프로토타입 빈의 count 필드값은 0이다.

4. 이제 clientBean은 프로토타입 빈을 내부 필드에 보관(참조)한다.

5. 클라이언트A는 clientBean을 스프링 컨테이너에 요청해서 받는다. 싱글톤이므로 항상 같은 clientBean이 반환된다.

6. 클라이언트 A는 clientBean.logic()을 호출한다.

7. clientBean은 prototypeBean의 addCount()를 호출해서 프로토타입 빈의 count를 증가한다. count값이 1이된다.

8. 클라이언트B는 clientBean을 스프링 컨테이너에 요청해서 받는다. 싱글톤이므로 항상 같은 clientBean이 반환된다.

9. 여기서 중요한 점이있는데, clientBean이 내부에 가지고 있는 프로토타입 빈은 이미 과거에 주입이 끝난 빈이다. 주입시점에 스프링 컨테이너에 요청해서 프로토타입 빈이 새로 생성이 된것이지, 사용할때마다 새로 생성되는 것이 아니다.

10. 클라이언트B는  clientBean.logic() 을 호출한다.

11. clientBean은 prototypeBean의 addCount() 를 호출해서 프로토타입 빈의 count를 증가한다. 원래 값이 1이기때문에 2가된다.

 

Test

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

    }

    @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
    static class ClientBean{
        private final PrototypeBean prototypeBean;

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

    }

    @Scope("prototype")
    static class PrototypeBean {
        private int count;

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

결과

22:09:53.247 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a451d4d
22:09:53.285 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
22:09:53.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
22:09:53.337 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
22:09:53.339 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
22:09:53.342 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
22:09:53.361 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'singletonWithPrototypeTest1.ClientBean'
PrototypeBean.init hello.core.scope.SingletonWithPrototypeTest1$PrototypeBean@7bd7d6d6
22:09:53.396 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'singletonWithPrototypeTest1.ClientBean' via constructor to bean named 'singletonWithPrototypeTest1.PrototypeBean'

Process finished with exit code 0

 

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

▶ 이럴경우  프로토타입빈을 사용할필요가있을까? 그냥 싱글톤 빈을 사용하는게 더 효율적이라생각된다.

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

 

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

ex) clientA, clientB가 각각 의존관계 주입을 받으면 각각 다른 인스턴스의 프로토타입 빈을 주입 받는다.

clientA → prototypeBean@x01

clientB prototypeBean@x02

물론 사용할때 마다 새로 생성되는 것은 아니다.

 

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

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

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

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

하지만 ObjectProvider는 ObjectFactory를 상속, 옵션, 스트림처리등 편의 기능이 많고, 별도의 라이브러리가 필요없으나, 스프링에

의존적이다.

JSR-330 Provider

라이브러리 추가 implementation 'javax.inject:javax.inject:1'  

   // Provider 라이브러리 추가
    @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을 통해 항상 새로운 프로토타입 빈이 생성된다.

 

강의출처 : 스프링 핵심 원리 - 기본편 - 인프런 | 강의 (inflearn.com)