Spring Bean 설정 - @Lazy , @Scope , @PostConstruct , @PreDestroy

이정수·2025년 10월 23일

Spring

목록 보기
14/18
  • Spring Bean의 초기화 방식
    @Lazy

  • Spring Bean의 Scope
    @Scope

  • Spring Bean의 생성 및 파괴 시 메서드 호출
    @PostConstruct , @PreDestroy

@Scope
Spring Bean은 각각 다른 Scope를 가질 수 있다.
@Scope 어노테이션을 통해 설정이 가능

  • Singleton : default
    @Scope(value= ConfigurableBeanFactory.SCOPE_SINGLETON)

  • Prototype
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)

@Lazy
。선언된 Spring BeanLazy Initialization 적용
▶ 해당 Spring Bean이 호출되는 시점에서 초기화하는 기법으로 권고 X

Spring Bean Life Cycle 어노테이션

  • @PostConstruct :
    Spring Bean 생성 및 의존성 주입이 완료된 직후 자동으로 호출할 Spring Bean초기화 메서드에 선언하는 어노테이션
    @PostConstruct가 선언된 메서드Spring Bean을 참조하기 전에 먼저 호출

    초기화 메서드는 주로 Spring Beanresource, default value, logging 을 설정하는 코드를 작성

  • @PreDestroy :
    Spring Context에서 Spring Bean파괴하기전 자동으로 호출할 cleanup method에 선언하는 어노테이션

    cleanup methodSpring Context가 보유하고 있는 Resource를 해제하는 용도로 사용
    Spring Bean이 삭제되기 전 @PreDestory로 선언된 cleanup method를 수행하여 활성화된 연결들을 모두 닫아야한다.

    cleanup 메서드는 주로 Spring BeanDB Connection 해제 , Resource 해제하는 코드를 작성
profile
공부기록 블로그

0개의 댓글