인프런 강의 < 스프링 핵심 원리 - 기본편 > 정리
애플리케이션과 데이터 베이스를 연결해 두는 것 - 3 way handshake 등이 오래걸리므로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 = 초기화 연결 메시지
객체 생성 -> 의존관계 주입 의 라이프사이클을 가진다.스프링 빈은 객체를 생성하고, 의존관계 주입이 다 끝난 다음에야 필요한 데이터를 사용할 수 있는 준비가 완료 된다스프링 컨테이너 생성 -> 스프링 빈 생성 -> 의존관계 주입 -> 초기화 콜백 -> 사용 - > 소멸전 콜백 -> 스프링 종료
- 초기화 콜백: 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출
- 소멸전 콜백: 빈이 소멸되기 직전에 호출
객체의 생성과 초기화를 분리하자public class NetworkClient implements InitializingBean, DisposableBean{
@Override
public void afterPropertiesSet() throws Exception {
connect();
call("초기화 연결 메시지");
}
@Override
public void destroy() throws Exception {
disConnect();
}
}
InitializingBean 인터페이스는 의존관계 주입이 완료 된 후DisposableBean 인터페이스는 소멸 직전 콜백 지원생성자 호출, url = null
NetworkClient.afterPropertiesSet
connect: http://hello-spring.dev
call: http://hello-spring.dev message = 초기화 연결 메시지
13:24:49.043 [main] DEBUG
org.springframework.context.annotation.AnnotationConfigApplicationContext -
Closing NetworkClient.destroy
close + http://hello-spring.dev
afterPropertiesSet가 호출 된다.@Bean(initMethod = " init", destroyMethod = "close") 처럼 초기화, 소멸 메서드를 지정할 수 있다.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")추가@Bean의 destroyMethod속성에는 추론이라는 기능이 있다close, shutdown을 사용한다.@Bean은 추론 기능을 사용해 close, shutdown 으로 되어있는 메소드를 자동으로 호출해준다.@Bean(destroyMethod = "")으로 하면 추론 기능을 사용하지 않는다.애노테이션 방법을 사용하자! @PostConstruct
public void init() {
System.out.println("NetworkClient.init");
connect();
call("초기화 연결 메시지");
}
@PreDestroy
public void close() {
System.out.println("NetworkClient.close");
disconnect();
}
javax.annotation.PostConstruct이며 스프링에 종송적인 기술이 아니라 JSR-250이라는 자바 표준이다. 따라서 다른 컨테이너에서도 동작한다.단점으로는 외부 라이브러리에는 적용하지 못한다.@PostConstruct, @PreDestroy를 사용하되, 외부 라이브러리는 @Bean의 initMethod, destroyMethod를 이용하자.< 자료 출처: 스프링 핵심 원리 - 기본편 >