빈 생명주기 콜백 - 인터페이스(InitializingBean, DisposableBean)

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

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

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

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

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

 

인터페이스(InitializingBean, DisposableBean)

-> InitialzingBean인터페이스는 afterPropertiesSet()메서드로 초기화를 지원한다.

-> DisposableBean인터페이스는 destroy()메서드로 소멸을 지원한다.

 

public class NetworkClient implements InitializingBean, DisposableBean {
    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);
    }

    @Override
    public void afterPropertiesSet() throws Exception { // 의존관계 주입이 끝나면 호출 -> 초기화
        System.out.println("NetworkClient.afterPropertiesSet()");
        connect();
        call("초기화 메시지");
    }

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


}

-> 결과

- 생성자가 호출되고, 의존관계 주입이 끝난 후 afterPropertiesSet()이 호출되어 초기화가 이루어지고, 스프링 컨테이너의 종료가 호출된 후 destroy()메서드가 호출되어 소멸되었다.

 

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

-> 초기화, 소멸 인터페이스는 스프링 전용 인터페이스로, 해당 코드가 스프링 전용 인터페이스에 의존하게 된다.

-> 초기화, 소멸 메서드의 이름을 변경할 수 없다. InitializingBean, DisposableBean로 사용해야 한다.

-> 코드를 개발자가 직접 고칠 수 없는 외부 라이브러리에는 적용할 수 없다.

 

※ 초기화, 소멸 인터페이스를 사용하여 초기화와 소멸을 하는 방법은 스프링 초창기에 나온 방법으로 현재는 더 좋은 방법들이 있기 때문에 거의 사용하지 않는다고 한다.

 

☆ 참고

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