본문 바로가기
Spring

빈 생명주기 콜백

by BottleCoffin 2022. 9. 1.

1. 빈 생명주기 콜백 시작

데이터베이스 커넥션 풀이나, 네트워크 소켓처럼 애플리케이션 시작 시점에 필요한 연결을 미리 해두고, 애플리케이션 종료 시점에 연결을 모두 종료하는 작업을 진행하려면, 객체의 초기화와 종료 작업이 필요하다.

 

스프링 빈은 객체를 생성하고, 의존관계 주입이 다 끝난 다음에야 필요한 데이터를 사용할 수 있는 준비가 완료된다.
따라서 초기화 작업은 의존관계 주입이 모두 완료되고 난 다음에 호출해야 한다. 


스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려주는 다양한 기능을 제공하고, 스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준기 때문에 안전하게 종료 작업을 진행할 수 있다.

 

 

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

스프링 컨테이너 생성 ➡ 스프링 빈 생성 ➡ 의존관계 주입 ➡ 초기화 콜백 사용 ➡ 소멸전 콜백(싱글톤) ➡ 스프링 종료
  • 초기화 콜백 : 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출
  • 소멸전 콜백 : 빈이 소멸되기 직전에 호출

 

 

❗ 객체의 생성과 초기화를 분리하자.

  • 생성자는 필수 정보(파라미터)를 받고, 메모리를 할당해서 객체를 생성하는 책임을 가진다. 반면에 초기화는
    이렇게 생성된 값들을 활용해서 외부 커넥션을 연결하는등 무거운 동작을 수행한다.
  • 따라서 생성자 안에서 무거운 초기화 작업을 함께 하는 것 보다는 객체를 생성하는 부분과 초기화 하는 부분을
    명확하게 나누는 것이 유지보수 관점에서 좋다. 물론 초기화 작업이 내부 값들만 약간 변경하는 정도로 단순한 경우에는 생성자에서 한번에 다 처리하는게 더 나을 수 있다.

 

싱글톤 빈은 스프링 컨테이너가 종료될 때 함께 종료되기 때문에 스프링 컨테이너 종료 직전에 소멸전 콜백이 일어난다.
반면 생명주기가 짧은 빈도 있는데 이 빈들은 컨테이너와 무관하게 해당 빈이 종료되기 직전에 소멸전 콜백이 일어난다. 

 

스프링은 크게 3가지 방법으로 빈 생명주기 콜백을 지원

  1. 인터페이스(InitializingBean, DisposableBean)
  2. 설정 정보에 초기화 메서드, 종료 메서드 지정
  3. @PostConstruct, @PreDestroy 애노테이션 지원

 

2. 인터페이스 InitializingBean, DisposableBean

 

// InitializingBean, DisposableBean => implements
public class BeanLifeCycleTest implements InitializingBean, DisposableBean {

	// 의존관계 주입이 끝나면 호출되는 메서드
    @Override
    public void afterPropertiesSet() throws Exception {

    }
    // 소멸시 호출되는 메서드
    @Override
    public void destroy() throws Exception {

    }
}

 

초기화, 소멸 인터페이스 단점

  • 이 인터페이스는 스프링 전용 인터페이스다. 해당 코드가 스프링 전용 인터페이스에 의존한다.
  • 초기화, 소멸 메서드의 이름을 변경할 수 없다.
  • 내가 코드를 고칠 수 없는 외부 라이브러리에 적용할 수 없다.

 

👉 스프링 초창기에 나온 방법으로 잘 사용하지 않는다.

 

 

 

3. 빈 등록 초기화, 소멸 메서드 지정

설정 정보에 @Bean(initMethod = "init", destroyMethod = "close") 처럼 초기화, 소멸 메서드를 지정 후

클래스에 해당 메소드들(init,close)를 작성

	@Configuration
    static class LifeCycleConfig {
        @Bean(initMethod = "init", destroyMethod = "close") // 추가
        public NetworkClient networkClient() {
        
        }
    }

설정 정보 사용 특징

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

 

종료 메서드 inferred (추론)

  • @Bean의 destroyMethod 는 기본값이 (inferred) (추론)으로 등록되어 있다.
  • 라이브러리는 대부분 close , shutdown 이라는 이름의 종료 메서드를 사용한다.
  • 추론 기능은 close , shutdown 라는 이름의 메서드를 자동으로 호출해준다. 이름 그대로 종료 메서드를 추론해서 호출해주기 때문에 직접 스프링 빈으로 등록하면 종료 메서드는 따로 적어주지 않아도 잘 동작한다.
  • 추론 기능을 사용하고 싶지 않을때는 destroyMethod=""  빈 공백을 지정하면 된다.
String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
더보기

The optional name of a method to call on the bean instance upon closing the application context, for example a close() method on a JDBC DataSource implementation, or a Hibernate SessionFactory object. The method must have no arguments but may throw any exception.
As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the @Bean method. For example, given an @Bean method returning an Apache Commons DBCP BasicDataSource, the container will notice the close() method available on that object and automatically register it as the destroyMethod. This 'destroy method inference' is currently limited to detecting only public, no-arg methods named 'close' or 'shutdown'. The method may be declared at any level of the inheritance hierarchy and will be detected regardless of the return type of the @Bean method (i.e., detection occurs reflectively against the bean instance itself at creation time).
To disable destroy method inference for a particular @Bean, specify an empty string as the value, e.g. @Bean(destroyMethod=""). Note that the org.springframework.beans.factory.DisposableBean callback interface will nevertheless get detected and the corresponding destroy method invoked: In other words, destroyMethod="" only affects custom close/shutdown methods and java.io.Closeable/AutoCloseable declared close methods.
Note: Only invoked on beans whose lifecycle is under the full control of the factory, which is always the case for singletons but not guaranteed for any other scope.

 

 

4. 애노테이션 @PostConstruct, @PreDestroy

가장 편리하게 초기화와 종료를 실행할 수 있다.

 

@PostConstruct, @PreDestroy 애노테이션 특징

  • 스프링에서 가장 권장하는 방법
  • 애노테이션 하나만 붙이면 되므로 매우 편리하다.
  • 패키지를 보면 javax.annotation.PostConstruct 이다. 스프링에 종속적인 기술이 아니라 JSR-250 라는 자바 표준이다. 따라서 스프링이 아닌 다른 컨테이너에서도 동작한다.
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
  • 컴포넌트 스캔과 잘 어울린다.

 

 

단점 : 외부 라이브러리에는 적용하지 못한다
외부 라이브러리를 초기화, 종료 시에는  @Bean의 기능을 사용하자.

 

 

👉 @PostConstruct, @PreDestroy 애노테이션을 사용하자

 

 

 

출처 : 
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8/dashboard

 

'Spring' 카테고리의 다른 글

스프링 부트와 JPA 활용1  (0) 2022.09.03
빈 스코프  (0) 2022.09.02
의존관계 자동 주입  (0) 2022.08.31
JPA 영속성 컨텍스트  (0) 2022.08.12
Spring Transaction  (0) 2022.07.23

댓글