스프링에는 스프링 빈이 생성되거나 소멸하기 직전에 메소드를 호출해줄 수 있는 기능이 있는데 크게 세가지 방식이 있다.
public class NetworkClient implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
connect();
call("초기화 연결 메세지");
}
@Override
public void destroy() throws Exception {
disconnect();
}
}
InitializingBean
인터페이스는 afterPropertiesSet()
메서드로 초기화 콜백을 지원하고 DisposableBean
인터페이스는 destroy()
메서드로 소멸 콜백을 지원한다.
@Configuration
static class LifeCycleConfig {
@Bean(initMethod = "init", destroyMethod = "close")
public NetworkClient networkClient() {
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
@Bean(initMethod = "init", destroyMethod = "close")
처럼 스프링 빈 설정 정보에서 초기화, 소멸 콜백 메소드를 지정해줄 수 있다.
destroyMethod
속성의 메소드 추론 기능@Bean
의 destroyMethod
의 기본값은 (inferred)
인데 close, shutdown
이라는 이름을 가진 메소드를 detroyMethod
로 추론해서 자동으로 호출해준다.public class NetworkClient
{
@PostConstruct
public void init() {
connect();
call("초기화 연결 메세지");
}
@PreDestroy
public void close() {
disconnect();
}
}
@PostConstruct
, @PreDestroy
어노테이션을 메소드 앞에 붙여서 초기화, 소멸 콜백 메소드로 지정할 수 있다.