빈 생명주기 콜백 - 3가지 방법

황준하·2023년 8월 17일

Spring 기본

목록 보기
34/38
post-thumbnail

인터페이스 InitializingBean, DisposableBean

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

설정 정보 사용 특징

  • 메서드 이름을 자유롭게 줄 수 있다.
  • 스프링 빈이 스프링 코드에 의존하지 않는다.
  • 코드가 아니라 설정 정보를 사용하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화, 종료 메서드를 적용할 수 있다.

종료 메서드 추론

  • @Bean의 destroyMethod 속성에는 아주 특별한 기능이 있다.
  • 라이브러리는 대부분 close, shutdown이라는 이름의 종료 메서드를 사용한다.
  • 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작한다.

애노테이션 @PostCDonstruct, @PreDestroy

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 애노테이션 특징

  • 최신 스프링에서 가장 권장하는 방법이다.
  • 애노테이션 하나만 붙이면 되므로 매우 편리하다.
  • 패키지를 보면 스프링에 종속적인 기술이 아니라 자바 표준이다. 따라서 스프링이 아닌 다른 컨테이너에서도 동작한다.
  • 컴포넌트 스캔과도 잘 어울린다.
  • 유일한 단점은 외부 라이브러리에는 적용하지 못한다는 것이다. 외부 라이브러리를 초기화, 종료 해야 하면 @Bean의 기능을 사용하자.

0개의 댓글