빈 스코프란?
간단히 말해서 빈이 존재할 수 있는 (유지될 수 있는) 범위이다.
스프링이 지원하는 스코프는 다음과 같다.
1. 싱글톤
기본 스코프로 스프링 컨테이너의 시작과 종료까지 유지되는 가장 넓은 범위의 스코프이다. 항상 같은 인스턴스의 스프링 빈을 반환한다. 아래의 예제로 이해해보자.
public class SingletonTest {
@Test
public 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")
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.PrototypeTest$SingletonBean@54504ecd
singletonBean2 = hello.core.scope.PrototypeTest$SingletonBean@54504ecd
SingletonBean.destroy
빈 초기화 메서드를 실행 → 같은 인스턴스 빈 조회 → 종료 메서드 호출
이러한 실행결과로 알 수 있듯이 싱글톤 빈은 스프링 컨테이너 생성 시점에 초기화 메서드가 실행되며, 싱글톤 빈은 스프링 컨테이너가 관리하기 때문에 스프링 컨테이너가 종료될 때 빈의 종료 메서드가 실행 된다.
2. 프로토타입
스프링 컨테이너가 프로토타입 빈의 생성과 의존관계 주입까지만 관여하고 더는 관리하지 않는 매우 짧은 범위의 스코프이다. 항상 새로운 인스턴스를 생성해서 반환한다. 아래 예시로 이해해보자.
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);
ac.close(); //종료
}
@Scope("prototype")
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@13d4992d
prototypeBean2 = hello.core.scope.PrototypeTest$PrototypeBean@302f7971
프로토타입 스코프의 빈은 스프링 컨테이너에서 빈을 조회할 때 생성되고, 초기화 메서드도 실행된다. 또한, 프로토타입 빈을 2번 조회 했으므로 완전히 다른 스프링 빈이 생성되고, 초기화도 2번 실행된 것을 확인할 수 있다.
하지만 프로토타입 빈은 스프링 컨테이너가 생성과 의존관계 주입 그리고 초기화 까지만 관여하고 더는 관리하지 않기에 스프링 컨테이너가 종료될때 @PreDestroy 같은 종료 메서드가 전혀 실행되지 않는다!
3. 웹 관련 스코프
스프링 웹과 관련된 기능이 들어가 있을수도 있는 스코프이다. 프로토타입과 다르게 스프링이 해당 스코프의 종료시점까지 관리한다. (종료 메서드가 호출된다)
request
HTTP 요청 하나가 들어오고 나갈 때 까지 유지되는 스코프. 각각의 HTTP 요청마다 별도의 빈 인스턴스가 생성되고 관리된다.
request 스코프는 언제쓰일까??
동시에 여러 HTTP 요청이 오게되면 정확히 어떤 요청이 남긴 로그인지 구분하기 어렵게되는데 이때 request 스코프를 사용하면 적절하다!! 아래 예제로 확인해보자.
@Component
@Scope(value = "request") // HTTP 요청당 하나씩 생성, HTTP 요청이 끝나는 시점에 소멸
public class MyLogger {
private String uuid;
private String requestURL;
// requestURL 은 이 빈이 생성되는 시점에는 알 수 없으므로 외부에서 setter로 입력 받는다.
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
public void log(String message) {
System.out.println("["+uuid+"]"+"["+requestURL+"]"+message);
}
@PostConstruct
public void init() { // 이 빈이 생성되는 시점에 자동으로 @PostConstruct 초기화 메서드를 사용해 uuid를 생성해서 저장해둔다.
uuid = UUID.randomUUID().toString();
System.out.println("["+uuid+"] request scope bean create : "+this );
}
@PreDestroy
public void close() { // 이 빈이 소멸되는 시점에 @PreDestroy 를 사용해서 종료 메시지를 남긴다.
System.out.println("["+uuid+"] request scope bean close : "+this );
}
}
session
HTTP Session과 동일한 생명주기를 가지는 스코프. 웹 세션이 생성되고 종료될 때 까지 유지된다.
application
서블릿 컨텍스트(ServletContext) 와 동일한 생명주기를 가지는 스코프.
websocket
웹 소켓과 동일한 생명주기를 가지는 스코프
참고
'Spring' 카테고리의 다른 글
@ModelAttribute의 역할! (0) | 2022.07.03 |
---|---|
Thread Pool 이란 도대체 무엇인가! (0) | 2022.06.17 |
빈 생명주기 콜백에 대해 알아보자 (0) | 2022.06.04 |
조회 빈이 2개 이상일 때 해결방법! (0) | 2022.06.04 |
[Springboot] Execution failed for task ':test' 에러 해결방법 (0) | 2022.06.04 |
댓글