[Spring 기본] 7. 빈 생명주기 콜백

heyhey·2023년 2월 6일
0

Spring

목록 보기
16/23

객체의 초기화와 종료작업이 필요할 때가 있다. 언제 어떤 방법으로 하는지 알아보도록 하자

예제로 네트워크에 연결이 된다 시점에 connect()를 호출해 연결을 하고
애플리케이션이 종료되면 disconnect로 연결을 끊으려고 한다.

public class NetworkClient {
    private String url;

    public NetworkClient(){
        System.out.println("생성자 호출, url :" + url);
        connect();
        call("초기화 연결 메시지")
    }

    public void setUrl(String url) {
        this.url = url;
    }
    // 서비스 시작
    public void connect(){
        System.out.println("connect:" + url);
    }
    // 메시지 출력
    public void call(String message) {
        System.out.println("call:" + url + "message:" + message);
    }
    // 서비스 종료
    public void  disconnect(){
        System.out.println("close : " + url);
    }
}

테스트 파일

public class BeanLifeCycleTest {
    @Test
    public void lifeCycleTest() {
        ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient client = ac.getBean(NetworkClient.class);
        ac.close();
    }

    @Configuration
    static class LifeCycleConfig {

        @Bean
        public NetworkClient networkClient() {
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
          }
    }
}

결과 =>

생성자 호출, url = null
connect : null
call : null, message: 초기화 연결메시지

url 정보가 없이 connect가 되고있다. 객체를 생성할 때 Url이 없었지 때문이다.

여기서 알 수 있는 라이프 사이클은 다음과 같다.

객체를 생성하고 => 의존관계가 주입된다.

따라서 초기화 작업은 의존관계가 주입이 모두 완료되고 나서 호출해야 한다.

스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려준다.

스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준다.

정리

스프링 빈의 이벤트 라이프 사이클

스프링 컨테이너 생성 => 스프링 빈 생성 => 의존관계 주입 => 초기화 콜백 => 사용 => 소멸전 콜백 => 스프링 종료

  • 초기화 콜백 : 빈이 생성되고 빈의 의존관계 주입이 완료된 후 호출
  • 소멸전 콜백 : 빈이 소멸되기 직전에 호출

빈 생명주기 콜백 방법


크게 3가지 방법으로 빈 생명주기 콜백을 사용할 수 있다.

인터페이스

public class NetworkClient implements InitializingBean, DisposableBean {
    ...

    @Override
    public void afterPropertiesSet() throws Exception {
      connect();
      call("초기화 연결 메시지");
    }

    @Override
    public void destroy() throws Exception {
        disConnect();
    }
}

InitializingBeanafterPropertiesSet() 메서드로 초기화를 지원한다.

DisposableBeandestroy() 메서드로 소멸을 지원한다.

초기화 소멸 인터페이스의 단점

  • 스프링 전용 인터페이스에만 의존한다.
  • 초기화, 소멸 메서드의 이름을 변경할 수 없다.
  • 내가 코드를 고칠 수 없는 라이브러리에 적용 불가하다.

=> 거의 사용안한다.

설정 정보다 초기화 메서드, 종료 메서드 지정

설정 정보에 @Bean(initMethod = "init", destroyMethod = "close") 처럼 초기화, 소멸 메서드를
지정할 수 있다. 메서드 이름을 자유롭게 사용 가능하다.

설정 정보에 초기화 소멸 메서드 지정

  @Configuration
  static class LifeCycleConfig {
      @Bean(initMethod = "init", destroyMethod = "close")
      public NetworkClient networkClient() {
          NetworkClient networkClient = new NetworkClient();
          networkClient.setUrl("http://hello-spring.dev");
          return networkClient;
} }

사용

  public void init() { 
    System.out.println("NetworkClient.init"); connect();
    call("초기화 연결 메시지");
  }
  public void close() {
      System.out.println("NetworkClient.close");
      disConnect();
  }

종료 메서드 추론

close()shutdown() 이라는 종료 메서드를 사용하면 destroyMethod 이 이러한 두 이름의 메서드를 자동으로 추론하여 호출하는 기능이 있다.

@PostConstruct, @PreDestroy 애노테이션 지원

이게 가장 사용하기 쉬운 방법인것 같다. 스프링에서 가장 권장하고 있는 방법이다.

@PostConstruct
public void init() {
  System.out.println("NetworkClient.init"); connect();
  call("초기화 연결 메시지");
  }

@PreDestroy
public void close() {
    System.out.println("NetworkClient.close");
    disConnect();
}

웬만하면 @PostConstruct, @PreDestroy 애노테이션을 사용하자
코드를 고칠 수 없는 외부 라이브러리를 초기화, 종료해야 하면 @Bean 의 initMethod , destroyMethod 를 사용하자.

profile
주경야독

0개의 댓글