ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring bean 정리(2)_Bean 생성과 singleton
    Spring Framework 2023. 8. 13. 15:48

    singleton

    • 객체를 딱 1번만 생성하고 싶을 때 사용하는 기법
    • 싱글톤 빈은 스프링 컨테이너에서 한 번만 생성되며, 컨테이너가 사라질 때 제거된다.
    • @Configuration은 @Bean에 추가 설정을 줘서 singleton을 보장한다.

     

    spring bean의 singleton 예시

    // singleton 보장함	
    @Configuration
    public class SampleConfig {
        @Bean
        public SampleService sampleService() {
            // code.. (A 객체 생성 로직)
        }
    
        @Bean
        public SubSampleService subSampleService() {
    		// code.. (A 객체 생성 로직)
        }
    }
    
    // singleton을 보장하지 않음
    @Component
    public class SampleConfig {
        @Bean
        public SampleService sampleService() {
            // code.. (A 객체 생성 로직)
        }
    
        @Bean
        public SubSampleService subSampleService() {
    		// code.. (A 객체 생성 로직)
        }
    }
    • sampleService와 subSampleService bean을 등록할때, 동일한 A객체가 생성된다고 가정하자.
      • 그렇다면 2개의 객체가 생성되어 singleton이 깨졌다고 보이지만, 실제로는 @Configuration의 라이브러리를 사용해 singleton을 보장한다.
        1. SampleConfig가 bean으로 등록이 될 때, SampleConfig를 상속받은 프록시 객체가 등록된다.
        2. 생성된 프록시 객체는 A객체가 이미 spring container에 등록이 되어있으면, 등록된 것을 찾아서 반환해준다.
        3. spring container에 없으면, A객체를 생성하고 container에 등록한다.

     

    • @Configuration의 라이브러리를 사용하기 때문에 @Configuration 어노테이션이 없다면 singleton이 보장되지 않는다.
    • bean을 수동으로 등록해도 singleton을 보장하지 못한다.

     

     

    출처)

    https://steady-coding.tistory.com/594

Designed by Tistory.