객체의 초기화와 종료작업이 필요할 때가 있다. 언제 어떤 방법으로 하는지 알아보도록 하자
예제로 네트워크에 연결이 된다 시점에 connect()를 호출해 연결을 하고
애플리케이션이 종료되면 disconnect로 연결을 끊으려고 한다.
public class NetworkClient {
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);
}
}
테스트 파일
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest() {
ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient client = 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 : null
call : null, message: 초기화 연결메시지
url 정보가 없이 connect가 되고있다. 객체를 생성할 때 Url이 없었지 때문이다.
여기서 알 수 있는 라이프 사이클은 다음과 같다.
따라서 초기화 작업은 의존관계가 주입이 모두 완료되고 나서 호출해야 한다.
정리
스프링 빈의 이벤트 라이프 사이클
스프링 컨테이너 생성 => 스프링 빈 생성 => 의존관계 주입 => 초기화 콜백 => 사용 => 소멸전 콜백 => 스프링 종료
크게 3가지 방법으로 빈 생명주기 콜백을 사용할 수 있다.
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()
메서드로 소멸을 지원한다.
=> 거의 사용안한다.
설정 정보에 @Bean(initMethod = "init", destroyMethod = "close")
처럼 초기화, 소멸 메서드를
지정할 수 있다. 메서드 이름을 자유롭게 사용 가능하다.
설정 정보에 초기화 소멸 메서드 지정
@Configuration
static class LifeCycleConfig {
@Bean(initMethod = "init", destroyMethod = "close")
public NetworkClient networkClient() {
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
} }
사용
public void init() {
System.out.println("NetworkClient.init"); connect();
call("초기화 연결 메시지");
}
public void close() {
System.out.println("NetworkClient.close");
disConnect();
}
close()
나 shutdown()
이라는 종료 메서드를 사용하면 destroyMethod
이 이러한 두 이름의 메서드를 자동으로 추론하여 호출하는 기능이 있다.
이게 가장 사용하기 쉬운 방법인것 같다. 스프링에서 가장 권장하고 있는 방법이다.
@PostConstruct
public void init() {
System.out.println("NetworkClient.init"); connect();
call("초기화 연결 메시지");
}
@PreDestroy
public void close() {
System.out.println("NetworkClient.close");
disConnect();
}
웬만하면 @PostConstruct, @PreDestroy 애노테이션을 사용하자
코드를 고칠 수 없는 외부 라이브러리를 초기화, 종료해야 하면 @Bean 의 initMethod , destroyMethod 를 사용하자.