[spring] 빈 초기화 콜백, 소멸 콜백

괭이밥·2022년 11월 5일

spring

목록 보기
5/10
post-thumbnail

🔎 목차

  1. 스프링 빈 콜백 사용하기
  2. 인터페이스 - InitializionBean, DisposableBean
  3. 메서드 지정- @Bean(initMethod, destroyMethod)
  4. 애노테이션 - @PostConstruct, @PreDestory


📌 스프링 빈 콜백 사용하기

스프링 빈 콜백

초기화 콜맥

  • 스프링 빈은 컨테이너에 등록된 후에 사용할 수 있다.
  • 등록된 후에 스프링 빈 초기화 작업을 위해 초기화 콜백 메서드을 사용한다.
  • 초기화 콜백 메서드는 스프링 빈 생성되고, 의존관계 주입이 완료된 후 호출된다.

소멸 콜백

  • 스프링 빈이 소멸되기 전에 호출된다.
  • 싱글톤의 경우 스프링 컨테이너가 종료되기 전에 호출된다.
  • 프로토타입의 경우 소멸 콜백이 호출되지 않는다.

콜백 메서드 사용 방법

  1. 인터페이스 - InitializionBean, DisposableBean
  2. 메서드 지정- @Bean(initMethod, destroyMethod)
  3. 애노테이션 - @PostConstruct, @PreDestory

테스트 예제 코드

  • 테스트 예제 코든느 아래와 같이 진행한다.
  • ac.close() : 스프링 컨테이너를 닫는다.
    • AnnotationConfigApplicationContext에서 지원하는 기능이다.
public class CallBackTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    void callBack(){
        MyBean myBean = ac.getBean(MyBean.class);
        myBean.logic();
        ac.close();
    }
}


🍃 인터페이스

InitializionBean, DisposableBean

  • InitializionBean 인터페이스
    • 초기화 콜백 메서드 제공
    • void afterPropertiesSet() : 의존관계 주입 끝나고 메소드 호출
  • DisposableBean 인터페이스
    • 소멸 콜백 메서드 제공
    • void destroy() : 스프링 빈 소멸 전에 메소드 호출

예시

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class RedMyBean implements MyBean, InitializingBean, DisposableBean {

    public void logic(){
        System.out.println("RedMyBean.logic");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("RedMyBean 소멸");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("RedMyBean 생성");
    }
}

테스트 실행

[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸

특징

  • 스프링 전용 인터페이스이다.
  • 초기화, 소멸 메서드 이름 변경이 불가능하다.


🍃 메서드 지정

@Bean(initMethod, destroyMethod)

  • @Bean(initMethod = "메서드명")
    • 초기화 콜백 메서드 직접 작성 후 스프링 빈에게 알려줌
    • 의존관계 주입 후 메서드 호출
  • @Bean(detroyMethod = "메서드명")
    • 소멸 콜백 메서드 직접 작성 후 스프링 빈에게 알려줌 (위와 동일)
    • 빈 소멸 전에 메서드 호출

예제

  • 초기화, 소멸 메서드 추가
public class RedMyBean implements MyBean {

    public void logic(){
        System.out.println("RedMyBean.logic");
    }

    public void destroy(){
        System.out.println("RedMyBean 소멸");
    }

    public void init(){
        System.out.println("RedMyBean 생성");
    }
}

  • 설정정보에 콜백 메서드 알리기
    • 수동 빈 등록
    • 이 때 RedMyBean에서 컴포넌트 스캔이 일어난다면 자동 빈 등록, 수동 빈 등록으로 중복 등록 충돌이 일어난다. @Component와 같은 애노테이션을 꼭 없애주도록 하자.
@Configuration
public class AppConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public MyBean myBean(){
        return new RedMyBean();
    }
}

실행

[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸

특징

  • 메서드 이름을 자유롭게 지을 수 있다.
  • 빈의 설정 정보를 이용한다.


🍃 애노테이션

@PostConstruct, @PreDestory

  • @PostConstruct
    • 초기화 메서드 위에 추가
  • @PreDestory
    • 소멸 메서드 위에 추가

예제

import org.springframework.stereotype.Component;

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

@Component
public class RedMyBean implements MyBean {

    public void logic(){
        System.out.println("RedMyBean.logic");
    }

    @PreDestroy // 애노테이션 추가
    public void destroy(){
        System.out.println("RedMyBean 소멸");
    }

    @PostConstruct // 애노테이션 추가
    public void initt(){
        System.out.println("RedMyBean 생성");
    }
}

실행

[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸

특징

  • 자바 공식에서 지원하는 기능이다.


출처
인프런 '스프링 핵심 원리 - 기본편' 강의

profile
개발도 하고 싶은 클라우드 엔지니어

0개의 댓글