스프링 핵심 원리/빈 생명주기 콜백
인터페이스 InitializingBean , DisposableBean
jeongdalma
2021. 1. 2. 02:23
Class
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 {
connect();
call("초기화 연결 메시지");
}
@Override
// 서버가 종료 될 때
public void destroy() throws Exception {
System.out.println("destory");
disconnect();
}
}
Test
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest(){
// 스프링 컨테이너 생성
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient bean = ac.getBean(NetworkClient.class);
// 스프링 컨테이너 종료
ac.close();
}
@Configuration
static class LifeCycleConfig{
@Bean
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
출력
생성자 호출 , url = null
Connect : http://hello-spring.dev
Call : http://hello-spring.dev message : 초기화 연결 메시지
destory
close : http://hello-spring.dev
초기화 소멸 인터페이스 단점
- 이 인터페이스는 스프링 전용 인터페이스다. 해당 코드가 스프링 전용 인터페이스에 의존한다.
- 초기화 , 소멸 메소드의 이름을 변경할 수 없다.
- 내가 코드를 고칠 수 없는 외부라이브러리에 적용할 수 없다.
인터페이스를 사용하는 초기화 , 종료 방법은 스프링 초창기에 나온 방법들이고 , 지금은 더 나은 방법들이 있어 거의 사용하지 않는다.
스프링 핵심 원리 - 기본편 - 인프런
스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다. 초급 프레임워크 및 라이브러리 웹 개발 서버 개발 Back-End Spring 객체지향 온
www.inflearn.com