> For the complete documentation index, see [llms.txt](https://yihyuns-gitbook.gitbook.io/today-i-learned/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yihyuns-gitbook.gitbook.io/today-i-learned/spring/bean_scope.md).

# Bean Scope (빈의 유효 범위)

## 빈 스코프

스코프란, 유효 범위를 뜻한다. 빈 스코프를 달리함으로써 빈의 생성, 사용, 소멸 시점을 달리할 수 있다. 빈 스코프는 다음의 5종류가 있다.

1. Singleton (기본)
2. Prototype
3. Request
4. Session
5. Application

## Singleton

싱글톤이란, 클래스의 인스턴스가 단 하나만 생성되도록 하는 디자인 패턴을 말한다.

스프링 컨테이너 내부의 빈들은 기본적으로 싱글톤으로 관리된다. 즉, 한 번만 생성되고 이것을 getBean을 통해 여러 곳에서 주입받아 이용하는 방식으로 운영된다.

Singleton의 경우 빈의 생성 주기는 다음을 따른다.

1. 스프링 컨테이너 생성
2. 빈 등록 및 의존성 주입
3. **초기화 콜백**
4. 빈 사용
5. **소멸 전 콜백**
6. 빈 소멸
7. 스프링 컨테이너 소멸

즉, 스프링 컨테이너가 생성된 직후 빈도 생성되고, 스프링 컨테이너가 소멸되기 직전 빈도 소멸된다.

## Prototype

빈 스코프를 프로토타입으로 지정하면 getBean 메서드를 호출할 때마다 새로운 객체를 생성하여 반환한다.

즉, 스프링 컨테이너는 빈의 생성 및 등록까지만 관여하고 이후의 생명주기에는 관여하지 않는다.

`유일하게 스프링 컨테이너가 소멸 시점을 관리해주지 않는 스코프 타입`인 것이다.

따라서, 빈 스코프를 프로토타입으로 지정하는 경우 `스프링 컨테이너의 소멸 시점에 함께 소멸되지 않기 때문에 개발자가 소멸 시점을 관리해야 함`에 주의해야 한다.

## Request

빈 스코프를 Request로 지정하면 HTTP 요청이 컨트롤러에 도착할 때 빈이 생성되고 HTTP 응답이 반환될 때 빈이 소멸한다.

## Session

빈 스코프를 Session으로 지정하면 웹 세션이 생성될 때 빈이 생성되고 웹 세션이 종료될 때 빈이 소멸한다.

## Application

빈 스코프를 Application으로 지정하면 웹 서블릿 컨텍스트가 생성될 때 빈이 생성되고 소멸할 때 빈이 소멸한다.

## 관리 범위 지정

@Scope 어노테이션을을 이용하면 된다.

```java
@Bean
@Scope("singleton") // default

@Bean
@Scope("prototype") // prototype
```

## 빈 스코프가 중요한 이유

빈 스코프에 따라 빈의 생성, 소멸 시점이 달라진다.

빈의 생성/소멸 시점을 확실하게 알면 해당 시점에 호출되는 콜백 함수를 통해 특정 로직(ex: Logging)을 수행할 수 있다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://yihyuns-gitbook.gitbook.io/today-i-learned/spring/bean_scope.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
