Spring / / 2024. 7. 7. 22:00

Bean Lifecycle

 

스프링의 가장 큰 특징이라고 생각되는 것은 DI, IoC 가 있습니다.

DI(Dependency Injection)과 IoC(Inveresion of Control) 은 개발자의 편의를 증가시키는데요

객체의 생성부터 소멸까지 개발자가 직접 코드로 관리하는 것이 아닌, 컨테이너(여기서는 스프링 컨테이너)가 관리해줍니다.

또한 빈 컨테이너에서 각 빈들은 싱글톤으로 관리되어 메모리 측면에서도 효율적인 모습을 보여줍니다

Bean 의 생성과 소멸 과정

  1. 인스턴스화
    • Spring 컨테이너가 Bean의 인스턴스를 생성합니다.
  2. 프로퍼티 설정
    • DI(Dependency Injection)을 통해 Bean의 프로퍼티 값을 설정합니다.
  3. 초기화 콜백
    • Bean을 사용할 준비가 완료되었음을 의미하는 콜백 함수를 호출합니다.
    • ‘@PostContruct’, InitializingBean 인터페이스의 afterPropertiesSet() 또는 init()메서드를 사용합니다.
  4. Bean 사용
    • 스프링 컨테이너에 등록된 빈을 BizLogic 등 적절한 곳에서 사용합니다.
  5. 소멸 콜백
    • 컨테이너가 종료되기 전 Bean의 정리 작업을 수행합니다.
    • ‘@PreDestroy’, DisposableBean의 destroy() 또는 custom destroy()를 사용합니다.
  6. 소멸
    • 위 과정이 끝난 후 Bean 인스턴스가 소멸하여 GC 됩니다.

다음은 위에서 설명한 Bean의 생성과 소멸 과정에 대해 코드로 살펴보겠습니다.

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class MyBean implements InitializingBean, DisposableBean {

    private DependencyBean dependencyBean;

    // 1. 인스턴스화 (Instantiation)
    public MyBean() {
        System.out.println("1. Bean 인스턴스화");
    }

    // 2. 프로퍼티 설정 (의존성 주입)
    @Autowired
    public void setDependencyBean(DependencyBean dependencyBean) {
        this.dependencyBean = dependencyBean;
        System.out.println("2. 의존성 주입");
    }

    // 3. 초기화 콜백 - @PostConstruct
    @PostConstruct
    public void postConstruct() {
        System.out.println("3-a. @PostConstruct 초기화");
    }

    // 3. 초기화 콜백 - InitializingBean
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("3-b. InitializingBean 초기화");
    }

    // 3. 초기화 콜백 - 커스텀 init 메서드
    public void customInit() {
        System.out.println("3-c. 커스텀 init() 메서드");
    }

    // 4. Bean 사용
    public void useBean() {
        System.out.println("4. Bean 사용");
    }

    // 5. 소멸 콜백 - @PreDestroy
    @PreDestroy
    public void preDestroy() {
        System.out.println("5-a. @PreDestroy 소멸");
    }

    // 5. 소멸 콜백 - DisposableBean
    @Override
    public void destroy() throws Exception {
        System.out.println("5-b. DisposableBean 소멸");
    }

    // 5. 소멸 콜백 - 커스텀 destroy 메서드
    public void customDestroy() {
        System.out.println("5-c. 커스텀 destroy() 메서드");
    }
}

@Configuration
class Config {
    @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
    public MyBean myBean() {
        return new MyBean();
    }
}

이 외에도 Bean 후처리기(BeanPostProcessor), Aware Interface, Bean Scope 등이 존재합니다.

'Spring' 카테고리의 다른 글

@Valid 검증 어노테이션  (0) 2024.07.21
Pagination  (0) 2024.07.14
Transaction Propagation  (2) 2024.06.30
ThreadLocal  (2) 2024.06.09
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유