Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

빈 스코프?? 본문

인프런/[인프런] Spring 핵심원리 이해

빈 스코프??

Seung__ 2021. 7. 30. 23:26

1. 빈 스코프??


  • 스프링 빈은 스프링 컨테이너의 시작과 함께 생성되어, 
  • 스프링 컨테이너가 종료될 때 까지 유지된다.
  • 이것은 스프링 빈이 싱글톤 "스코프"로 생성되기 때문이다. 
  • 스코프는 빈이 존재할 수 있는 범위를 의미함

 

2. 스코프 종류?


  • 싱글톤 : 기본 스코프, 스플이 컨테이너의 시작~종료까지 유지되는 가장 넓은 범위의 스코프
  • 프로토타입 : 스프링 컨테이너는 프로토타입 빈의 생성과 의존 관계 주입까지만 관여하고,
    더는 관리하지 않는 매우 짧은 범위의 스코프, 초기화 까지 해줌. -->종료메서드 호출 안됨.
  • 웹 관련 스코프
    - request : 웹 요청이 들어오고 나갈 때 까지 유지되는 스코프
    - session : 웹 세션이 생성되고 종료될 때 까지 유지되는 스코프
    - application : 웹의 서블릿 컨텍스트와 같은 범위로 유지되는 스코프

 

 

3. 프로토타입 스코프


  • 싱글톤 스코프의 빈을 조회하면 항상 같은 인스턴스의 스프링 빈을 반환해.
  • 근데 프로토타입 스코프를 스프링 컨테이너에서 조회하면
    항상 새로운 인스턴스 생성, DI, 초기화 까지만 처리!반환 후 더이상 관리 안함.
  • 즉 요청하는 시점에 인스턴스 생성하고 의존관계 넣어주고, 초기화 해주고! 리턴하고 컨테이너에서 버림.
  • 요청이 또 오면 그때 생성하고, DI하고, 리런 후 컨테이너에서 버림..
  • 따라서 프로토타입 빈을 관리하는 책임은 클라이언트에 있다!
  • 그래서 @PreDestroy 호출되지 않음
  •  

 

4. singleton Bean Test


public class SingletonTest {

    @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);
        Assertions.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 통과

SingletonBean.init
singletonBean1 = hello.core.scope.SingletonTest$SingletonBean@6c4980d3
singletonBean2 = hello.core.scope.SingletonTest$SingletonBean@6c4980d3
23:07:59.825 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@32ee6fee, started on Fri Jul 30 23:07:59 KST 2021
SingletonBean.destroy

 

 

5. prototype bean test


public class PrototypeTest {

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

        Assertions.assertThat(prototypeBean1).isNotSameAs(prototypeBean2);

        ac.close();
    }


    @Scope("prototype")
    @Component
    static class PrototypeBean{

        @PostConstruct
        public void init(){
            System.out.println("PrototypeBean.init");
        }

        @PreDestroy
        public void destroy(){
            System.out.println("PrototypeBean.destroy");
        }
    }
}
  • 프로토 타입 빈은 요청할 때 마다 생성되는 것을 확인했다. --> 매 번 생성하니 참조값이 다르다.
  • 생성 후 @PostConstruct까지 진행 된다.
  • 프로토 타입 빈은 스프링 컨테이너가 관리하지 않기 때문에
    스프링 컨테이너 종료 시점에 @PreDestroy과 같은 종료 메서드는 실행되지 않는다.
find prototypeBean1
PrototypeBean.init
find prototypeBean2
PrototypeBean.init
prototypeBean1 = hello.core.scope.PrototypeTest$PrototypeBean@14fc1f0
prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@4ae9cfc1
23:19:24.735 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@32ee6fee, started on Fri Jul 30 23:19:24 KST 2021
  • 직접 종료하는 방법 :  destroy를 직접 호출.
prototypeBean.destroy();
prototypeBean2.destroy();

 

 

5. 프로토타입 빈 특징


  • 스프링 컨테이너에 요청할 때 마다 인스턴스 새로 생성
  • 스플이 컨테이너는 프로토타입 빈 생성, 의존관계 주입, 초기화 까지만 관여함
  • 종료 메서드 실행 안함
  • 따라서 프로토타입을 요청한 클라이언트가 직접 관리해야함. 종료메서드도 직접 호출해야함.

 

 

6. GitHub : 210730 ProtoTypeBean


 

GitHub - bsh6463/SpringCoreFunction

Contribute to bsh6463/SpringCoreFunction development by creating an account on GitHub.

github.com

 

Comments