import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class NetworkClient implements InitializingBean, DisposableBean {
private String url; //접속해야할 서버 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);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("NetworkClient.afterPropertiesSet");
connect();
call("초기화 연결 메세지"); //의존관계주입 끝난 후
}
@Override
public void destroy() throws Exception {
System.out.println("NetworkClient.destroy");
disconnect();
}
}
- InitializingBean은 afterPropertiesSet() 메서드로 초기화를 지원한다. - DisposableBean은 destroy() 메소드로 소멸을 지원한다.
출력결과
- 출력결과를 보면 초기화 메서드가 주입 완료 후에 적절하게 호출된 것을 볼 수 있다. - 스프링 컨테이너의 종료가 호출되자 소멸 메서드가 호출된 것을 확인할 수 있다.
초기화, 소멸 인터페이스 단점 - 이 인터페이스는 스프링 전용 인터페이스다. 해당 코드는 스프링 전용 인터페이스에 의존한다. - 초기화,소멸 메서드의 이름을 변경할 수 없다. - 내가 고칠 수 없는 외부 라이브러리에 적용하 수 없다. 이 방법은 스프링 초창기 방법이고 지금은 더 나은 방법이 있어 거의 사용하지 않는다.
2) 빈 등록 초기화, 소멸 메서드
설정 정보에 @Bean(initMethod = "init",destroyMethod = "close") 처럼 초기화, 소멸 메서드를 지정할 수 있다.
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(initMethod = "init",destroyMethod = "close") //메서드 지정
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://meenoi-spring.dev");
return networkClient;
}
}
}
public class NetworkClient {
private String url; //접속해야할 서버 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();
}
}
출력결과
설정 정보 사용 특징 - 메서드 이름을 자유롭게 줄 수 있다. - 스프링 빈이 스프링에 코드에 의존하지 않는다. - 코드가 아니라 설정정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 종료 메서드를 적용할 수 있다.
종료 메서드 추론 - 라이브러리는 대부분 close, shutdown이라는 종료 메서드를 사용한다. - @Bean의 destroyMethod 속성은 기본값이(inferred)(추론)으로 등록되어 있다. - 이 기능은 close, shutdown 라는 이름의 메서드를 자동으로 호출해준다. 이름 그대로 종료 메서드를 추론해서 호출한다. - 따라서 직접 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작한다. - 추론 기능을 사용하기 싫으면 destroyMethod =""처럼 빈 공백으로 지정하면 된다.
3)애노테이션@PostConstruct,@PreDestroy
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
public class NetworkClient {
private String url; //접속해야할 서버 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);
}
@PostConstruct
public void init() {
System.out.println("NetworkClient.init");
connect();
call("초기화 연결 메세지"); //의존관계주입 끝난 후
}
@PreDestroy
public void close() {
System.out.println("NetworkClient.close");
disconnect();
}
}
import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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://meenoi-spring.dev");
return networkClient;
}
}
}
출력결과
-@PostConstruct,@PreDestroy 이 두 애노테이션을 사용하면 가장 편리하게 초기화와 종료를 실행할 수 있다.
특징 - 최신 스프링에서 권장하는 방법이다. - 애노테이션 하나만 붙이면 되므로 매우 편리하다. - import jakarta.annotation.PostConstruct; 는 스프링에 종속적이지 않고 다른 컨테이너에서도 사용가능하다 - 컴포넌트스캔과 잘 어울린다. - 유일한 단점은 외부 라이브러리에 적용하지 못한다는 것이다. 그럴땐 두번째 방법을 사용하자.
정리 - @PostConstruct,@PreDestroy 애노테이션을 사용하자 - 코드를 고칠 수 없는 라이브러리를 초기화, 종료해야하면 @Bean의 initMethod,destroyMethod를 사용하자