오봉이와 함께하는 개발 블로그
Spring - 빈 스코프(빈 스코프란?, 프로토타입 스코프) 본문
728x90
빈 스코프란?
스프링 빈이 스프링 컨테이너의 시작과 함께 생성되어 스프링 컨테이너가 종료될 때 까지 유지된다 알고 있었다.
하지만 이것은 스프링 빈이 기본적으로 싱글톤 스코프로 생성되기 때문이다.
스코프는 번역 그대로 빈이 존재할 수 있는 범위를 뜻한다.
스프링이 지원하는 스코프
- 싱글톤 스코프
- 기본 스코프
- 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프
- 프로토타입
- 스프링 컨테이너는 프로토타입 빈의 생성과 의존관계 주입, 초기화 메소드까지만 관여하고 클라이언트에게 반환해 더는 관리하지 않는 매우 짧은 범위의 스코프
- 웹 관련 스코프
- request : 웹 요청이 들어오고 나갈때 까지 유지
- request로 들어와서 response로 나갈때 까지 유지
- session : 웹 세션이 생성되고 종료될 때 까지 유지
- application : 웹의 서블릿 컨텍스트와 같은 범위로 유지
- request : 웹 요청이 들어오고 나갈때 까지 유지
등록 방법
컴포넌트 스캔 자동 등록
@Scope("prototype")
@Component
public class HelloBean {}
수동 등록
@Scope("prototype")
@Bean
PrototypeBean HelloBean() {
return new HelloBean();
}
프로토타입 스코프
싱글톤 스코프의 빈을 조회하면 컨테이너는 항상 같은 인스턴스의 스프링 빈을 반환한다.
반면 프로토타입 스코프 빈을 조회하면 컨테이너는 항상 새로운 인스턴스를 생성해서 반환한다.
싱글톤 빈 요청
- 싱글톤 스코프의 빈을 스프링 컨테이너에 요청
- 스프링 컨테이너는 관리하는 스프링 빈을 반환
- 이후 같은 요청이 오면 같은 객체 인스턴스의 스프링 빈 반환
프로토타입 빈 요청
- 프로토타입 스코프의 빈을 컨테이너에 요청
- 스프링 컨테이너는 이 시점 프로토타입 빈을 생성하고 필요한 의존관계 주입
- 스프링 컨테이너는 생성한 프로토타입 빈을 클라이언트에 반환
- 이후 같은 요청이 들어오면 항상 새로운 프로토타입 빈을 생성해서 반환
정리
스프링 컨테이너는 프로토타입 빈을 생성하고 DI, 초기화까지만 처리한다.
이후 클라이언트에 빈을 반환하고, 스프링 컨테이너는 생성됐던 프로토타입 빈을 관리하지 않는다.
프로토타입 빈을 관리할 책임은 클라이언트로 넘어가기 때문에 @PreDestroy같은 종료 메소드가 호출되지 않는다.
싱글톤 스코프 빈 테스트
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);
assertThat(singletonBean1).isSameAs(singletonBean2);
ac.close();
}
@Scope("singleton")
// @Component가 없는 이유는 AnnotationConfigApplicationContext(SingletonBean.class); 에서 지정을 했기 때문
static class SingletonBean {
@PostConstruct
public void init() {
System.out.println("SingletonBean.init");
}
@PreDestroy
public void destroy() {
System.out.println("SingletonBean.destroy");
}
}
}
SingletonBean.init
singletonBean1 = hello.core.scope.SingletonTest$SingletonBean@5ddf0d24
singletonBean2 = hello.core.scope.SingletonTest$SingletonBean@5ddf0d24
18:38:09.485 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@32502377, started on Sun Jun 12 18:38:09 KST 2022
SingletonBean.destroy
- 빈 초기화 메소드 실행
- 같은 인스턴스의 빈 조회
- 종료 메소드 정상 호출
프로토타입 스코프 빈 테스트
public class PrototypeTest {
@Test
public 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);
assertThat(prototypeBean1).isNotSameAs(prototypeBean2);
// prototypeBean1.destroy();
// prototypeBean2.destroy();
// 직접 닫아주는 메소드
ac.close();
}
@Scope("prototype")
// @Component가 없는 이유는 AnnotationConfigApplicationContext(PrototypeBean.class); 에서 지정을 했기 때문
static class PrototypeBean {
@PostConstruct
public void init() {
System.out.println("PrototypeBean.init");
}
@PreDestroy
public void destroy() {
System.out.println("PrototypeBean.destroy");
}
}
}
find prototypeBean1
PrototypeBean.init
find prototypeBean2
PrototypeBean.init
prototypeBean1 = hello.core.scope.PrototypeTest$PrototypeBean@363a52f
prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@60856961
18:49:22.207 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2c1b194a, started on Sun Jun 12 18:49:22 KST 2022
- 스프링은 스프링 컨테이너 생성 시점에 초기화 메소드가 실행 되지만, 프로토타입 스코프의 빈은 스프링 컨테이너에서 빈을 조회할 때 생성되고 초기화 메소드도 실행됨
- 프로토타입 빈을 두 번 조회했으므로 완전 다른 스프링 빈이 생성되고, 초기화도 두 번 실행된 것 확인 가능
- 싱글톤 빈은 스프링 컨테이너가 관리하기 때문에 빈의 종료 메소드가 실행되지만, 프로토타입 빈은 스프링 컨테이너가 생성, 의존관계 주입, 초기화 까지만 관여하고 더는 관리하지 않음
- 때문에 프로토타입 빈은 스프링 컨테이너가 종료될 때 @PreDestroy같은 종료 메소드 실행되지 않음.
프로토타입 빈 정리
- 스프링 컨테이너에 요청될 때 마다 새로 생성
- 스프링 컨테이너는 프로토타입 빈의 생성, 의존관계 주입, 초기화까지만 관여
- 종료 메소드 호출되지 않음
- 그래서 프로토타입 빈은 조회한 클라이언트가 직접 관리해야 함.
- 종료 메소드 호출도 클라이언트가 직접 해야한다.
출처 : 인프런 김영한 지식공유자님의 스프링 완전 정복 로드맵 강의
728x90
'BE > Spring' 카테고리의 다른 글
Spring - 빈 스코프(프로토타입 스코프 - 싱글톤 빈과 함께 사용시 Provider로 문제 해결) (0) | 2022.06.13 |
---|---|
Spring - 빈 스코프(프로토타입 스코프 - 싱글톤 빈과 함께 사용시 문제점) (0) | 2022.06.13 |
Spring - 빈 생명주기 콜백(인터페이스 InitializingBean & DisposableBean, 빈 등록 초기화 & 소멸 메소드, 어노테이션 @PostConstruct & @PreDestroy (0) | 2022.06.11 |
Spring - 빈 생명주기 콜백(빈 생명주기 콜백 시작) (0) | 2022.06.11 |
Spring - 의존관계 자동 주입(조회한 빈이 모두 필요할 때 List&Map, 자동 등록?수동 등록? 올바른 운영 기준) (0) | 2022.06.11 |
Comments