FrameWork/Spring&Spring-boot
Spring 기본 30 - 인터페이스 IntializingBean, DisposableBean
Surge100
2023. 11. 29. 11:03
인터페이스 InitializingBean, DisaposableBean
NetworkClient implements InitializingBean, DisposableBean
package com.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);
connect();
call("초기화 연결 메시지");
}
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");
System.out.println("url = " + url);
connect();
call("초기화 연결 메시지");
}
@Override
public void destroy() throws Exception {
System.out.println("NetworkClient.destroy");
disconnect();
}
}
출력결과
- 출력 결과를 보면 초기화 메서드가 주입 완료 후에 적절하게 호출 된 것을 확인할 수 있다.
- 그리고 스프링 컨테이너 종료가 호출되자 소멸 메서드가 호출 된 것도 확인할 수 있다.
초기화, 소면 인터페이스 단점
- 이 인터페이스는 스프링 전용 인터페이스다. 해당 코드가 스프링 전용 인터페이스에 의존한다.
- 초기화, 소멸 메서드의 이름을 변경할 수 없다.
- 커스텀이 불가능한 외부 라이브러리에 적용할 수 없다.
➕참고
인터페이스를 사용하는 초기화, 종료 방법은 스프링 초창기에 나온 방법들로, 최근에는 더 나은 방법들이 있어 거의 사용하지 않는다.
[출처 - 스프링 핵심 원리 - 기본편]
스프링 핵심 원리 - 기본편 - 인프런 | 강의
스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., 스프링 핵심 원리를 이해하고, 성장하는 백엔드 개발자가 되어보세요! 📢
www.inflearn.com