[스프링 핵심원리] - 7. 빈 생명주기 콜백 (2)

Chooooo·2022년 11월 7일
0
post-thumbnail

이 글은 강의 : 김영한님의 - "스프링 핵심원리 - 기본편"을 듣고 정리한 내용입니다. 😁😁


스프링 빈 생명주기 콜백 지원 방법

  • 인터페이스(InitializingBean, DisposableBean)
  • 설정 정보에 초기화 메서드, 종료 메서드 지정
  • @PostConstruct, @PreDestroy 어노테이션 지원

인터페이스 InitializingBean, DisposableBean

  • NetworkClient 코드 수정
    NetworkClient가 InitializingBean 과 DisposableBean 인터페이스를 implements 하도록 코드를 수정한다.
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; // 접속해야할 서버 url

    // 디폴트 생성자
    public NetworkClient() {
        System.out.println("생성자를 호출, url = " + 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: afterPropertiesSet() 메서드로 초기화 지원

DisposableBean: destroy() 메서드로 소멸 지원

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

🎈 해당 코드가 스프링 전용 인터페이스(InitializingBean, DisposableBena)에 의존
🎈 초기화, 소멸 메서드의 이름 변경X.

  • 초기화 메서드 명 = afterPropertiesSet, 소멸 메서드 명 = destroy
    🎈 내가 코드를 고칠 수 없는 외부 라이브러리에 적용X

(참고) 인터페이스를 사용하는 초기화, 종료 방법은 스프링 초창기에 나온 방법으로, 지금은 다음의 더 나은 방법들이 있어서 거의 사용하지 않는다.

profile
back-end, 지속 성장 가능한 개발자를 향하여

0개의 댓글