[Spring] Bean Scope

Jeongyeon Park·2022년 11월 11일
0

Spring 개념 정리

목록 보기
1/4

Spring Bean


1. Spring Bean 이란

  • Spring에서 사용하는 POJO(Plain, Old Java Object) 기반 객체
  • Spring Application의 핵심을 이루는 객체로, Spring IoC(Inversion Of Control) 컨테이너에 의해 인스턴스화/관리/생성
  • 컨테이너에 공급하는 설정 메타 데이터(XML 파일 or Gradle)에 의해 생성 -> 컨테이너에게 Bean의 생성, Bean Life Cycle, Bean Dependency(종속성) 등의 정보 제공

2. Spring Bean 속성

Maven

  • XML 파일(application.xml)에 정의
  • 속성
    - class: 정규화된 자바 클래스 이름
    - id: Bean 식별자
    - scope: 객체의 범위 (Singleton, Prototype 등)
    - constructor-arg: 생성자에 전달할 파라미터
    - property: Bean Setter에 전달할 파라미터
    - init / destroy method
<bean id="xxx" class="xxx.yyy.zzz" scope="singleton" >
	<property name="message" value="Spring Bean"/>
</bean>

Spring Bean Scope


1. Bean Scope 특징

  • Scope를 설정하여 Bean이 관리되는 범위를 결정
  • 별도의 선언이 없으면 기본적으로 Singleton으로 생성

2. Bean Scope 종류

  • Singleton
    하나의 Bean에 대해서 Spring IoC Container 내에 하나의 객체만 존재

  • Prototype
    하나의 Bean에 대해서 Spring IoC Container 내에 다수의 객체 존재 가능

  • Request
    하나의 Bean에 대해서, 하나의 HTTP Request 라이프사이클 안에서는 하나의 객체만 존재 (= 각 HTTP Request는 고유한 Bean을 하나씩 가짐)

  • Session
    하나의 Bean에 대해서, 하나의 HTTP Session 라이프사이클 안에서는 하나의 객체만 존재 (= 각 HTTP Session은 고유한 Bean을 하나씩 가짐)

  • Global Session
    하나의 Bean에 대해서, 하나의 Global HTTP Session 라이프사이클 안에서는 하나의 객체만 존재 (= 각 Global HTTP Session은 고유한 Bean을 하나씩 가짐)
    (+ 일반적으로 Portlet Context 안에서 유효)

Request, Session, Global Session은 MVC Web Application 에서만 유효


3. Spring에서의 Scope 설정

Bean으로 등록하는 Class에 Annotation으로 Scope를 설정해줄 수 있다.

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;


@Component
@Service("userBean")
@Scope("prototype")
public class UserController {
}


References

0개의 댓글

관련 채용 정보