↩뒤로가기

설정 정보에 @Bean(initMethod = “init”, destroyMethod = “close”)처럼 초기화, 소멸 메소드를 직접 지정할 수도 있다.

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

package hello.core.lifecycle;

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://test.test>");
            return networkClient;
        }

    }

결과

생성자 호출, url = null
NetworkClient.init
connect: <http://test.test>
call: <http://test.test> message: 초기화 연결 메시지
13:24:45.294 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@43dac38f, started on Sat Mar 25 13:24:45 GMT+09:00 2023
NetworkClient.close
close: <http://test.test>

설정 정보 사용 트깅

종료 메소드 추론