새발블로그
[Spring] Bean Scope & 생명주기 본문
Bean Scope란?
스프링 컨테이너에서 Bean이 생성되고 존재하는 범위를 의미. 기본은 singleton.
주요 스코프 비교
| Scope | 설명 | 사용 예 |
| singleton | 한 개만 생성, 모든 요청 공유 | 대부분 서비스 Bean에 사용 |
| prototype | 요청마다 새로 생성 | 상태를 갖는 객체 필요 시 |
| request | HTTP 요청마다 Bean 생성 | 웹 애플리케이션 컨트롤러 등 |
| session | HTTP 세션마다 Bean 생성 | 로그인 정보 등 세션 유지 필요 시 |
생명주기 어노테이션
@PostConstruct
public void init() {
// 초기화 로직
}
@PreDestroy
public void destroy() {
// 종료 전 로직
}
- @PostConstruct: 의존성 주입 후 초기화
- @PreDestroy: 컨테이너 종료 전 정리 작업
예시 코드
@Component
@Scope("prototype")
public class LogBean {
@PostConstruct
public void init() {
System.out.println("Bean 초기화");
}
@PreDestroy
public void destroy() {
System.out.println("Bean 종료");
}
}
주의사항: prototype Bean 관리
- @PreDestroy 호출 안됨!
- 수동으로 종료 처리 필요
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
LogBean log = context.getBean(LogBean.class);
context.close(); // destroy() 호출 안 됨
→ DisposableBean, @PreDestroy로는 관리 불가
'Server > Spring' 카테고리의 다른 글
| [Spring] Spring 어노테이션 (0) | 2025.07.11 |
|---|---|
| [Spring] Spring MVC (0) | 2025.07.08 |
| [Spring] 의존성 주입 (Dependency Injection) (0) | 2025.07.08 |
| [Spring] Component Scan (컴포넌트 스캔) (0) | 2025.07.08 |
| [Spring] Bean 등록 방식 (수동 vs 자동) (0) | 2025.07.08 |