Spring Framework/[인프런] Spring 핵심 원리

Chapter 08. 빈 생명주기(Bean Life Cycle) 콜백

계란💕 2022. 8. 16. 12:48

8.1 빈 생명주기 콜백 시작

 

빈 생명주기 콜백 시작

  • 데이터베이스 커넥션 풀이나 네트워크 소켓처럼 애플리케이션 시작 시점에 필요한 연결을 미리해두고 애플리케이션 종료 시점에 연결을 모두 종료하는 작업을 진행하려면 객체의 초기화종료 작업이 필요하다.
  • ex) 외부 네트워크에 미리 연결하는 객체를 하나 생성한다고 가정할 때, 실제로 네트워크에 연결하는것은 아니고 단순히 문자만 출력하도록 했다. 이 'NetworkClient'는 애플리케이션 시작 시점에  'connect()'를 호출해서 연결을 맺어두어야하고 애플리케이션이 종료되면 'disconnect()'를 호출해서 연결을 끊어야한다.
  • 스프링 빈은 '객체 생성' => '의존 관계 주입' 과 같은 라이프 사이클을 사진다.

 

  Ex)

    - NetoworkClient를 만든다.

<hide/>
package hello.core.lifecycle;
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);
    }
}

 

    - 테스트 클래스 만들기

      -> ApplicationContext 를 닫아야하는데 ApplicationContext에는 close()가 없기 때문에AnnotationConfigApplicationContext 로 객체를 만들거나 인터페이스 ConfigurableApplicationContext 로 만들어야한다.

      -> ApplicationContext 아래에 ConfigurableApplicationContext 가 있고 그 아래에 AnnotationConfigApplicationContext 인터페이스가 있다.

<hide/>
package hello.core.lifecycle;
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://hello-spring.dev");
            return networkClient;
        }
    }
}

 

  Note) 실행결과

    - url정보 없이 connect가 호출되니까 null로 나온다.

 

  • 스프링 빈은 '객체 생성' => '의존 관계 주입'과 같은 라이프사이클을 가진다
  • 스프링 빈은 객체를 생성하고 의존관계 주입이 끝난 다음에야 필요한 데이터를 사용할 수 있는 준비가 완료된다.
  • 따라서, 초기화 작업은 의존 관계  주입이 모두 완료되고 난 다음에 호출해야한다.
    • 개발자가 의존관계 주입이 완료된 시점을 어떻게 알까?
    • 스프링은 의존관계 주입이 완료되면 스프링 빈에세 콜백 메서드를 통해 초기화 시점을 알려주는 다양한 기능 제공
    • 스프링은 스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준다. 
  • (싱글톤의 경우) 스프링 빈의 이벤트 라이프 사이클: 스프링 컨테이너 생성 => 스프링 빈 생성 => 의존관계 주입 => 초기화 콜백 => 사용 => 소멸 전 콜백 => 스프링 종료
  • 초기화 콜백: 빈이 생성되고 빈의 의존관계 주입이 완료된 후, 호출
  • 소멸 전 콜백: 빈이 소멸되기 직전에 호출된다.

 

 

객체의 생성과 초기화를 분리하는게 좋은 이유

  • 생성자는 필수 정보를 받고 메모리를 할당해서 객체를 생성, 초기화는 생성된 값들을 활용해서 외부 커넥션을 연결하는 등 외부 커넥션을 연결하는 등 무거운 동작을 수행한다.
  • 따라서, 함께 작업하기 보다는 명확하게 나누는 것이 유지보수 관점에서 좋다.

 

스프링이 빈 생명주기 콜백을  지원하는 방법

  • 인터페이스(InitializingBean, DisposableBean)
  • 설정 정보에 초기화 메서드, 종료 메서드 지정
  • @PostConstructor, @PreDestroy 애너테이션 지원

 

 

8.2 인터페이스 InitializaionBean, DisposableBean

 

  Ex) 앞서 본 예제 수정하기

    - NetworkClient가 InitiallizingBean(초기화 빈)을 구현하도록 한다.

      -> 구현해야하는 메서드 중 afterPropertiesSet()는 의존관계 주입이 끝난 다음에 호출되는 메서드로 초기화를 지원한다.

    - DisposableBean 인터페이스를 구현해서 destroy()를 구현하도록 한다. 소멸을 지원한다. 

<hide/>
package hello.core.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class NetworkClient implements InitializingBean, DisposableBean {

    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);
    }

    // 의존 관계 주입 후
   @Override
    public void afterPropertiesSet() throws Exception {
       System.out.println("NetworkClient.afterPropertiesSet");
        connect();
        call("초기화 연결 메시지");
    }

    // 빈이 종료될 때
    @Override
    public void destroy() throws Exception {
        disconnect();
    }
}

 

<hide/>
package hello.core.lifecycle;
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://hello-spring.dev");
            return networkClient;
        }
    }
}

fds  Note) 실행결과

    - 생성자 호출하는 단계에서는 당연히 url이 없다.

    - 생성 & 의존 관계 주입까지 끝난 다음에 connect()가 호출된다.

    - 디버그 로그를 보면 클로징 호출된다. 컨테이너가 종료하기 전에 싱글톤 빈들이 하나씩 죽을 때 destroy()가 호출된다.

 

 

 

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

  • 스프링 전용 인터페이스라서 내 코드가 스프링 전용 인터페이스에 의존적으로 설계해야한다.
  • 초기화, 소멸 메서드의 이름을 변경할 수 없다.
  • 내가 코드를 고칠 수 없는 외부 라이브러리에 적용할 수 없다.
  • 인터페이스를 이용해서 초기화, 종료 하는 방법은 예전에 쓰던 방법이고 최근에는 더 나은 방법이 있어서 사용하지 않는다.

 

 

 

8.3 빈 등록 초기화, 소멸 메서드

  • 설정정보에 @Bean(initMethod = "init", destroyMethod = "close") 처럼 초기화, 소멸 메서드를 지정할 수 있다.

  Ex) 설정 정보를 사용하도록 변경

    - 테스트 클래스

<hide/>
package hello.core.lifecycle;
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(initMethod = "init", destroyMethod = "close")
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }
}

  

<hide/>
package hello.core.lifecycle;
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();
    }
}

 

  Note) 실행결과

    - 스프링 컨테이너의 종료가 호출되자 소멸 메서드가 호출된 것을 확인할 수 있다. 

 

 

설정 정보 사용 특징

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

 

 

종료 메서드 추론

  • @Bean의 destroyMethod 속성에는 특별한  기능이 있다. 
  • 라이브러리는 대부분 close, shutdown 이라는 이름의 종료 메서드를 사용한다.
  • @Bean의 destroyMethod는 기본값이 (inferred) 추론으로 등록되어 있다.
    • 추론 기능은 close(), shutdown() 라는 이름의 메서드를 자동으로 호출해준다. 
    • 종료 메서드를 추론해서 호출해준다.
    • 따라서, 직접 스프링 빈으로 등록하면 종료 메서드를 따로 적어주지 않아도 잘 동작한다.

 

 

 

8.4 애너테이션 - @PostConstruct, @PreDestroy

 

@PostConstruct, @PreDestroy

  • 간단하고 편리해서 최신 스프링에서 권장하는 방법이다.
  • 스프링에 종속적인 기술이 아니라 자바 표준 기술이다. 따라서 다른 컨테이너에서도 동작한다.
  • 컴포넌트 스캔과도 잘 어울린다. 
  • 단점은 외부 라이브러리에는 적용하지 못한다는 점이다. 외부 라이브러리를 초기화, 종료해야하면 @Bean의 기능을 사용해야한다.
  • 코드를 고칠 수 없는 외부 라이브러리를 초기화, 종료 해야하면 @Bean의 'initMethod', 'destroyMethod'를 사용한다.

 

  Ex) PostConstruct, PreDestroy

    - 애너테이션을 추가한다.

<hide/>
package hello.core.lifecycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
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();
    }
}

 

    - 기존에 있던 @Bean의 매개변수 initMethod, destroyMethod를 지운다.

<hide/>
package hello.core.lifecycle;
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://hello-spring.dev");
            return networkClient;
        }
    }
}

  Note) 실행결과

 

 

 

 

 

출처 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/

 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...

www.inflearn.com