package hello.core.lifecycle;
import ...
public class NetworkClient implements InitializingBean, DisposableBean {
...
@Override
public void afterPropertiesSet() throws Exception {
connect();
call("초기화 연결 메세지");
}
@Override
public void destroy() throws Exception {
disconnect();
}
}
Log
생성자 호출, url = null
connect: null
call: null message = 초기화 연결 메세지
connect: http://hello-spring.dev
call: http://hello-spring.dev message = 초기화 연결 메세지
...
close http://hello-spring.dev
초기화, 소멸 인터페이스 단점
인터페이스를 사용하는 초기화, 종료 방법은 스프링 초창기에 나온 방법들로, 지금은 거의 사용하지 않는다.
설정정보에 @Bean(initMethod = "init", destroyMethod = "close")처럼 초기화, 소멸 메서드를 지정할 수 있다.
package hello.core.lifecycle;
public class NetworkClient {
...
public void init() {
System.out.println("NetworkClient.init");
connect();
call("초기화 연결 메세지");
}
public void close() {
System.out.println("NetworkClient.close");
disconnect();
}
}
BeanLIfeCycleTest
package hello.core.lifecycle;
import ...
public class BeanLifeCycleTest {
...
@Configuration
static class LifeCycleConfig {
@Bean(initMethod = "init", destroyMethod = "close")
public NetworkClient networkClient() {
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
Log
생성자 호출, url = null
connect: null
call: null message = 초기화 연결 메세지
NetworkClient.init
connect: http://hello-spring.dev
call: http://hello-spring.dev message = 초기화 연결 메세지
...
NetworkClient.close
close http://hello-spring.dev
설정 정보 사용 특징
종료 메서드 추론
package hello.core.lifecycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
...
@PostConstruct
public void init() {
System.out.println("NetworkClient.init");
connect();
call("초기화 연결 메세지");
}
@PreDestroy
public void close() {
System.out.println("NetworkClient.close");
disconnect();
}
}
@PostConstruct, @PreDestroy 애노테이션 특징