개발일기장

Spring 공부 06. singleton, prototype 본문

Spring Boot

Spring 공부 06. singleton, prototype

게슬 2023. 7. 12. 20:42
728x90

Spring은 Bean을 관리하면서 singleton으로 하는데 어떤 요청에도 처음 생성했던, 같은 인스턴스 객체를 반환함  

그래서 Spring Container가 객체생성, 주입, Bean초기화  ~~ Bean 소멸, Spring Container 종료 될때까지 관리를 해줌 

 

그리고 기본적으로 Spring은 singleton으로 돌아감..

@Scope("singleton")

이걸로 선언해주면 된다고 하는데 Bean의 Default값임

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

그래서 위의 테스트를 통과하게 되있음 (같은 객체임)


prototype은 Spring 이 의존관계까지만 주입해주고 그 이후로는 손을 안씀.

@Scope("prototype")
    @Test
    void prototypeBeanFind(){
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class);
        PrototypeBean prototypeBean1 = ac.getBean(PrototypeBean.class);
        System.out.println("prototypeBean1 = " + prototypeBean1);

        PrototypeBean prototypeBean2 = ac.getBean(PrototypeBean.class);
        System.out.println("prototypeBean2 = " + prototypeBean2);

        assertThat(prototypeBean1).isNotEqualTo(prototypeBean2);

        ac.close();
    }

그래서 위의 테스트의 경우 isNotEqualTo니깐 테스트를 통과함


Singleton 객체에 prototype 객체를 주입하게 되면 그게 다 깨져버리니깐 주의를 해야함

Provider같은 라이브러리도 있지만 prototype 객체의 경우에는 주의해서 사용하기.

728x90
Comments