설정 정보에 @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>
@Bean의 destroyMethod속성에는 아주 특별한 기능이 있다.close, shutdown 이라는 이름의 종료 메소드를 사용한다.@Bean의 destroyMethod는 기본값이 (inferred)(추론)으로 등록되어 있다.close, shutdown 이라는 이름의 메소드를 자동으로 찾아 호출해준다. 이름 그대로 종료 메소드를 추론하는 것이다.destoryMethod=””처럼 공백으로 지정하면 된다.