본문 바로가기
Spring

[스프링 핵심 원리 - 기본편] 빈 등록 초기화, 소멸 메서드

by 박성민 2021. 9. 20.

설정 정보에 @Bean(initMethod = "init", destroyMethod = "close")처럼 초기화, 소멸 메서드를 지정할 수 있습니다.

설정 정보를 사용하도록 변경

public class NetworkClient {

    private String url;

    public NetworkClient() {
        System.out.println("생성자 호출, url = " + url);
    }

    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 void init() {
        System.out.println("NetworkClient.init");
        connect();
        call("초기화 연결 메시지");
    }

    public void close() {
        System.out.println("NetworkClient.close");
        disconnect();
    }

}

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

@Configuration
static class LifeCycleConfig {

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

}

결과

생성자 호출, url = null
NetworkClient.init
connect: http://hello-spring.dev
call : http://hello-spring.dev message = 초기화 연결 메시지
23:13:25.130 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4bb33f74, started on Mon Sep 20 23:13:24 KST 2021
NetworkClient.close
close http://hello-spring.dev

설정 정보 사용 특징

  • 메서드 이름을 자유롭게 줄 수 있습니다.
  • 스프링 빈이 스프링 코드에 의존하지 않습니다.
  • 코드가 아니라 설정 정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 종료 메서드를 적용할 수 있습니다.

종료 메서드 추론

  • @Bean의 destroyMethod 속성에는 아주 특별한 기능이 있습니다.
  • 라이브러리는 대부분 close, shutdown이라는 이름의 종료 메서드를 사용합니다.
  • @Bean의 destroyMethod는 기본값이 (inferred)(추론)으로 등록되어 있습니다.
  • 이 추론 기능은 close, shutdown라는 이름의 메서드를 자동으로 호출해줍니다. 이름 그대로 종료 메서드를 추론해서 호출해줍니다.
  • 따라서 직접 스프링으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작합니다.

참조

댓글