빈 생명주기 콜백 - 빈 등록 초기화, 소멸 메서드

2023. 8. 23. 23:16Spring/[inflearn]스프링 핵심 원리 - 기본편

-> 스프링에는 3가지 방법의 빈 생명주기 콜백을 지원한다.

1. 인터페이스(InitializingBean, DisposableBean)

2. 설정 정보에 초기화 메서드, 종료 메서드 지정

3. @PostConstruct, @PreDestroy 애너테이션

 

◎ 빈 등록 초기화, 소멸 메서드 지정

-> 설정 정보에 @Bean(initMethod = "init", destroyMethod = "close")와 같이 초기화와 소멸 메서드를 지정할 수 있다. 해당 코드에서는 초기화 메서드를 "init", 소멸 메서드를 "close"라는 이름으로 지정하였다.

 

public class NetworkClient{
    private String url; // 접속할 서버의 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() throws Exception { // 의존관계 주입이 끝나면 호출 -> 초기화
        System.out.println("NetworkClient.init");
        connect();
        call("초기화 메시지");
    }

    public void close() throws Exception { // 빈이 종료될 때 호출 -> 소멸
        System.out.println("NetworkClient.close");
        disconnect();
    }


}

-> 테스트 코드

public class BeanLifeCycle {
    @Test
    public void lifeCycleTest(){
        ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient client = ac.getBean(NetworkClient.class);
        ac.close(); // 스프링 컨테이너 종료

    }

    @Configuration
    static class LifeCycleConfig{
        @Bean(initMethod = "init", destroyMethod = "close") // 초기화, 소멸 메서드 지정
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://lifecycle.com");
            return networkClient;
        }
    }
}

-> 결과

 

설정 정보 사용 특징

-> 초기화, 소멸 메서드의 이름을 자유롭게 지정할 수 있다.

-> 스프링 빈이 스프링 코드에 의존하지 않는다.

-> 코드가 아닌 설정 정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 소멸 메서드를 적용할 수 있다.

 

◎ 종료 메서드 추론

-> @Bean의 destroyMethod에는 추론 기능이 있다.

@Bean의 destroyMethod

-> @Bean의 destroyMethod를 들어가보면 INFER_METHOD라고 작성되어 있다.

-> AbstractBeanDefinition 클래스의 INFER_METHOD를 보면 "(inffered)"라고 되어있다.

AbstractBeanDefinition 클래스의 INFER_METHOD

-> 추론 기능은 @Bean 설정 정보를 통해 destroyMethod를 close 혹은 destroy로 지정하면 이 이름을 추론해서 메서드를 알아서 호출해준다.

-> 직접 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 알아서 잘 동작한다.

-> 추론 기능을 사용하지 않으려면 destroyMethod = ""로 지정하면 된다.

 

 

☆ 참고

[인프런]스프링 핵심 원리 - 기본편