Post

[Spring] 싱글톤 & 프로토타입 Bean Scope

스프링 프레임워크에서 빈(Bean)의 스코프(Scope)는 빈이 생성되고, 존재하며, 관리되는 방식을 정의한다. 각 스코프는 빈의 생명주기와 가용성을 결정한다.

주요 빈 스코프 (Bean Scope)

  1. 싱글톤(Singleton)
    • 스프링 프레임워크의 기본 스코프
    • 스프링 컨테이너당 빈의 인스턴스가 하나만 생성된다.
    • Application 전체에서 공유되는 단일 인스턴스를 제공한다.
  2. 프로토타입(Prototype)
    • 빈에 대한 요청이 있을 때마다 새로운 인스턴스가 생성된다.
    • 생성된 빈의 생명주기는 스프링 컨테이너에 의해 관리되지 않는다. 즉, 생성 이후 컨테이너가 빈을 관리하지 않는다.
  3. 리퀘스트(Request)
    • 웹 애플리케이션에서 사용
    • 각 HTTP 요청마다 빈의 새 인스턴스가 생성된다.
    • 하나의 HTTP 요청 내에서는 모든 구성요소가 동일한 인스턴스를 공유한다.
  4. 세션(Session)
    • 웹 애플리케이션에 사용
    • 각 HTTP세션마다 빈의 새 인스턴스가 생성된다.
    • 하나의 HTTP세션 내에서는 모든 구성요소가 동일한 인스턴스를 공유한다.
  5. 글로벌 세션(Global Session)
    • 주로 포털 애플리케이션에 사용된다.
    • 전체 애플리케이션에 공유되는 글로벌 HTTP세션 스코프이다.

싱글톤(Singleton) & 프로토타입(Prototype) 비교

인스턴스 생성

싱글톤은 하나의 인스턴스만을 생성하고 공유하지만, 프로토타입은 요청마다 새로운 인스턴스를 생성한다.

메모리 사용

싱글톤은 하나의 인스턴스만 유지하기 때문에 메모리 사용이 더 효율적일 수 있다.

상태 관리

싱글톤은 상태를 공유하지만, 프로토타입은 각 인스턴스가 독립적인 상태를 가질 수 있다.

생명주기 관리

싱글톤 빈은 컨테이너에 의해 전체 생명주기가 관리되지만, 프로토타입 빈은 생성과 의존성 주입 이후에는 컨테이너에 의해 관리 되지 않는다.

싱글톤 & 프로토타입 스코프 사용 예제

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
@Component
class NormalClass {

}

@Scope(value =ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
class PrototypeClass {

}

@Configuration
@ComponentScan
public class BeanScopesLauncherApplication {
	public static void main(String[] args) {
		try (var context = new AnnotationConfigApplicationContext
				(BeanScopesLauncherApplication.class)) {

			System.out.println(context.getBean(NormalClass.class));
			System.out.println(context.getBean(NormalClass.class));

			System.out.println(context.getBean(PrototypeClass.class));
			System.out.println(context.getBean(PrototypeClass.class));
			System.out.println(context.getBean(PrototypeClass.class));
		} catch (BeansException e) {
			e.printStackTrace();
		}
	}
}
1
2
3
4
5
6
// 출력
com.app.LearnSpringFramewordStart.examples.e1.NormalClass@76b07f29
com.app.LearnSpringFramewordStart.examples.e1.NormalClass@76b07f29
com.app.LearnSpringFramewordStart.examples.e1.PrototypeClass@38af9828
com.app.LearnSpringFramewordStart.examples.e1.PrototypeClass@376a0d86
com.app.LearnSpringFramewordStart.examples.e1.PrototypeClass@62656be4

주소값을 확인

프로토타입: Spring IoC 컨테이너당 객체 인스턴스가 여러개 일 수 있다.

싱글톤: Spring IoC 컨테이너당 객체 인스턴스가 딱 하나이다.

This post is licensed under CC BY 4.0 by the author.

© chanho. Some rights reserved.