본문 바로가기

Backend/Spring

[Spring] 빈 생명주기 콜백

인프런의 <스프링 핵심 원리 - 기본편>을 듣고 공부 용도로 정리한 글 입니다. 

 

 

애플리케이션 시작 시점에 필요한 연결을 미리 해두고, 애플리케이션 종료 시점에 연결을 모두 종료하는 작을 위해 객체의 초기화 작업과 종료 작업이 필요하다.

스프링에서는 이 작업을 어떻게 진행하는 지 알아보자.

 

예제: NetworkClient는 애플리케이션 시작 시점에 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);
    }

}

test 코드

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 = 초기화 연결 메시지

connect 될 때 url이 설정되지 않은 것을 확인할 수 잇다. 생성자 호출 시점에는 당연히 setUrl()이 호출되지 않아 이런 문제가 생기게 된다. 즉 객체를 생성하고 의존관계 주입까지 끝나고 나서 setUrl을 통해 url을 초기화 해주어야 하는데 어떻게 가능할까?

 

스프링은 객체 생성 -> 의존관계 주입 단계의 라이프사이클을 갖는다. url 초기화 같은 초기화 작업은 의존관계 주입까지 모두 완료된 후 진행되어야 하는데 개발자가 이 시점을 어떻게 알 수 있을까?

스프링은 의존관계 주입이 끝나면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려주고, 종료되기 전에는 소멸 콜백을 줘 종료 작업을 안전하게 작업할 수 있도록 한다.

 

* 스프링 빈의 이벤트 라이프 사이클

스프링 컨테이너 생성 -> 스프링 빙 생성 -> 의존관계 주입 -> 초기화 콜백 -> 사용 -> 소멸전 콜백 -> 스프링 종료

 

 

스프링에서는 크게 3가지 방법으로 빈 생명주기 콜백을 지원한다.

1. 인터페이스 (InitializingBean, DisposableBean) -> 사용 안함 ( 스프링 전용 인터페이스로 외부 라이브러리에 적용 불가)

2. 설정 정보에 초기화 메서드, 종료 메서드 지정 

3. @PostConstruct, @PreDestroy 애노테이션지원

 

1번은 사용하지 않으므로 넘어가겠다. 

 

 

빈 등록 초기화, 소멸 매서드 지정

@Bean(initMethod = "init", destroyMethod = "close") 로 초기화, 소멸 메서드를 지정할 수 있다.

public class NetworkClient {
    private String 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();
    }
}

설정 정보에 초기화 소멸 메서드 지정

    @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의 destroyMethod 속성은 기본값이 (inferred)로 등록되어 close, shutdown이라는 이름의 메서드를 자동으로 호출하여 준다. 따라서 종료 메서드는 직접 적어주지 않아도 위의 이름을 찾아서 동작한다. 

 

 

애노테이션 @PostConstruct, @PreDstroy

public class NetworkClient {
    private String 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();
    }
}

@PostConstruct, @PreDestroy 두 애노테이션을 사용하면 쉽게 초기화와 종료를 실행할 수 있어 최신 스프링에서 가장 권장하는 방법이다.

특히 스프링에 종속적인 기술이 아닌 자바 표준 기술로 스프링이 아닌 다른 컨테이너에서도 동작한다.

단점 : 외부 라이브러리에는 적용하지 못한다. 

 

*정리*

기본적으로 @PostConstruct, @PreDestroy 애노테이션을 사용하자!

만약 외부 라이브러리를 초기화, 종료해야 할 경우에는 @Bean의 initMethod, destroyMethod를 사용하자!

 

'Backend > Spring' 카테고리의 다른 글

[Spring] 빈 스코프  (0) 2023.03.02
[Spring] 의존관계 자동 주입  (0) 2023.02.19
[Spring] 컴포넌트 스캔  (0) 2023.02.17
[Spring] 싱글톤 컨테이너  (0) 2023.02.13
[Spring] 스프링 컨테이너와 스프링 빈  (0) 2023.02.13