-
Spring Bean 스코프Java, Kotlin, Spring 2022. 6. 19. 17:25
Bean 의 스코프
Singleton
하나의 Bean 정의에 대해서 Spring IOC Container 내에 단 하나의 객체만 존재한다.
Prototype
하나의 Bean 정의에 대해서 다수의 객체가 존재할 수 있다.
Request
하나의 Bean 정의에 대해서 하나의 HTTP request의 생명주기 안에 단 하나의 객체만 존재한다. 즉, 각각의 HTTP request는 자신만의 객체를 가진다. Web-aware Spring ApplicationContext 안에서만 유효하다.
Session
하나의 Bean 정의에 대해서 하나의 HTTP Session의 생명주기 안에 단 하나의 객체만 존재한다. Web-aware Spring ApplicationContext 안에서만 유효하다.
Global session
하나의 Bean 정의에 대해서 하나의 global HTTP Session의 생명주기 안에 단 하나의 객체만 존재한다. 일반적으로 portlet context 안에서 유효하다. Web-aware Spring ApplicationContext 안에서만 유효하다.
Application
하나의 Bean 정의에 대해서 ServletContext의 생명주기 안에 단 하나의 객체만 존재한다. Web-aware Spring ApplicationContext 안에서만 유효하다.
주의할 점
Singleton 모드인 bean 내부에 Prototype bean 을 사용하면, 항상 같은 bean 을 사용하게 된다.
이유는?
Singletone 모드인 bean은 ApplicationContext가 처음 로드된 이후로 항상 같은 인스턴스를 사용하게 된다. 이 때 내부의 참조 bean들도 모두 생성하기 때문에 Prototype bean으로 선언되어 있다고 하더라도 최초 생성된 bean 만 사용하게 된다.
해결 방법은?
Prototype bean에 ScopedProxyMode.TARGET_CLASS 옵션을 주면 된다.
@Component @Scope(value = "prototype", proxy = ScopedProxyMode.TARGET_CLASS) public class PrototypeBean {}
반응형'Java, Kotlin, Spring' 카테고리의 다른 글
Spring Data 분석하기 - 1편 소개 (0) 2022.08.11 Spring data mongodb multiple database config 설정하기 (0) 2022.06.24 Java 8 주요 업그레이드 사항 (0) 2022.05.25 JVM 메모리 구조 (0) 2022.05.20 @SpringBootApplication 어노테이션 (0) 2022.05.20