먼저 인터페이스로 초기화랑 소멸전 콜백을 받는 방법을 공부해보았다.

 

package hello.core.lifecycle;

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

public class NetworkClient implements InitializingBean, DisposableBean {

    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);
    }

    @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();
    }
}

이전 코드와 달라진 점은  InitializingBean, DisposableBean 인터페이스들은 implements 하고 있고

 

afterProperisesSet() 는 초기화를 지원한고

destroy() 는 소멸을 지원한다.

 

 

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

 

이 인터페이스는 스프링 전용 인터페이스이다. 해당 코드가 스프링 전용 인터페이스에 의존한다.

초기화, 소멸 메서드의 이름을 변경할 수 없다

내가 코드를 고칠 수 없는 외부 라이브러리에 적용할 수 없다.

 

이런 단점들에 의해서 거의 사용하지 않는 방법이다.

+ Recent posts