HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/
Spring
Spring
/
🎧
Spring Framework 핵심개념(Core)
/
🧪
Bean Scope & Bean Lifecycle Callback
🧪

Bean Scope & Bean Lifecycle Callback

Bean Scope

notion image
  • prototype으로 하면 매 생성마다 새로운 객체를 생성함
  • 빈이 생성되고, 존재하고, 적용되는 범위가 빈 스코프임
    • 싱글톤은 컨테이너 내에 한 개의 오브젝트만
    • 리퀘스트 : 웹을 통해 새로운 HTTP 요청이 생길 때마다 생성
 

Bean Lifecycle Callback

Spring-Bean LifeCycle
notion image

Bean life cycle event 제어하는 방법

  1. InitializingBean and DisposableBean callback interfaces
  1. Aware interfaces for specific behavior
  1. Custom init() and destroy() methods in bean configuration file
  1. @PostConstruct and @PreDestroy annotations

Bean 생성 생명주기 콜백

  1. @PostConsturct 어노테이션이 적용된 메소드 호출
  1. Bean 이 InitializingBean 인터페이스 구현시 afterPropertiesSet호출
  1. @Bean 어노테이션의 initMethod 에 설정한 메소드 호출

Bean 소멸 생성주기 콜백

  1. @PreDestroy 어노테이션이 적용된 메서드 호출
  1. Bean이 DisposableBean 인터페이스 구현시 destroy 호출
  1. @Bean 어노테이션의 destroyMethod 에 설정한 메소드 호출
@Repository @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) public class MemoryVoucherRepository implements VoucherRepository, InitializingBean, DisposableBean { private final Map<UUID, Voucher> storage = new ConcurrentHashMap<>(); @Override public Optional<Voucher> findById(UUID voucherId) { return Optional.ofNullable(storage.get(voucherId)); } @Override public Voucher insert(Voucher voucher) { storage.put(voucher.getVoucherId(), voucher); return voucher; } @PostConstruct public void postConstruct(){ System.out.println("postConstruct Called!"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet called!"); } @Override public void destroy() throws Exception { System.out.println("destroy called!"); } @PreDestroy public void preDistroy(){ System.out.println("preDestroy called!"); } }
@Configuration public class AppConfiguration{ @Bean(initMethod = "init") public BeanOne beanOne(){ return new BeanOne(); } } class BeanOne{ public void init(){ } }