빈 초기화 작업과 종료

정병웅·2024년 3월 14일
0

back-end

목록 보기
2/2

김영한 강사님의 스프링 핵심원리 강의를 들은 후 복습을 위해 작성한 글입니다 📖

스프링 빈 라이프 사이클

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

라이프 사이클에 대한 설명

초기화 콜백 : 빈이 생성 된 후 의존 관계 주입이 완료 된 후에 호출
소멸전 콜백 : 빈이 소멸 되기 전에 호출

빈 생명주기 콜백 사용 방법

  1. 설정 정보에 초기화 메서드, 종료 메서드 지정
  2. @PostConstruct, @PreDestroy 애노테이션 사용

설정 정보에 초기화 메서드, 종료 메서드 지정 예제

public class HttpClient {
    private String url;

    public HttpClient() {
        System.out.println("생성자 호출, url = " + url);

    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void connect() {
        System.out.println("connect url = " + url);
    }

    public void call(String message) {
        System.out.println("call message = " + message + " call url : " + url);
    }

    public void disconnect() {
        System.out.println("close url = " + url);
    }
    // 종료 시점 호출
    public void close() {
        System.out.println("NetworkClient.close");
        disconnect();
    }
    // 빈 생성 후 의존성 주입까지 완료 된 시점 후에 호출
    public void init() {
        connect();
        call("초기화 연결 메시지");
    }
}
public class BeanLifeCycle {
    @Test
    public void beanLifeCycleTest() {
    // @Configuration 이 붙은 클래스의 설정 정보를 읽어와 객체 생성
        ConfigurableApplicationContext ac = 
        new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        // 빈으로 등록된 HttpClient.class를 가져옴
        ac.getBean(HttpClient.class);
        // 스프링 컨테이너 종료
        ac.close();
    }
    @Configuration
    static class LifeCycleConfig {
    	// httpClient를 Bean으로 등록
        @Bean(initMethod = "init", destroyMethod = "close")
        public HttpClient httpClient() {
            HttpClient httpClient = new HttpClient();
            httpClient.setUrl("http://www.naver.com");
            return httpClient;
        }
    }
}

출력 결과

생성자 호출, url = null
connect url = http://www.naver.com
call message = 초기화 연결 메시지 call url : http://www.naver.com
22:27:17.585 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@60704c, started on Thu Mar 14 22:27:17 KST 2024
NetworkClient.close
close url = http://www.naver.com

  1. 빈으로 등록된 httpClient를 생성하고, 이때 url 값은 없기 때문에 null이 출력
  2. 생성 후 initMethod라는 속성에 빈 초기화 후 콜백할 함수의 명을 명시해준다. 따라서 init 메서드에 정의된 connect 함수의 call message 로그가 출력된다.
  3. 스프링 컨테이너가 종료 되면서 빈 소멸 전 콜백 함수를 destroyMethod에 명시 해준다. 따라서 close에 정의된 disconnect() 메서드가 실행된 후 소멸 한다.

@PostConstruct, @PreDestroy 애노테이션 사용

public class HttpClient {
    private String url;

    public HttpClient() {
        System.out.println("생성자 호출, url = " + url);

    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void connect() {
        System.out.println("connect url = " + url);
    }

    public void call(String message) {
        System.out.println("call message = " + message + " call url : " + url);
    }

    public void disconnect() {
        System.out.println("close url = " + url);
    }
    // 종료 시점 호출
    @PreDestroy
    public void close() {
        System.out.println("NetworkClient.close");
        disconnect();
    }
    // 빈 생성 후 의존성 주입까지 완료 된 시점 후에 호출
    @PostConstruct
    public void init() {
        connect();
        call("초기화 연결 메시지");
    }
}
public class BeanLifeCycle {
    @Test
    public void beanLifeCycleTest() {
        ConfigurableApplicationContext ac = 
        new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        ac.getBean(HttpClient.class);
        ac.close();
    }
    @Configuration
    static class LifeCycleConfig {
        @Bean
        public HttpClient httpClient() {
            HttpClient httpClient = new HttpClient();
            httpClient.setUrl("http://www.naver.com");
            return httpClient;
        }
    }
}

출력 결과

생성자 호출, url = null
connect url = http://www.naver.com
call message = 초기화 연결 메시지 call url : http://www.naver.com
22:27:17.585 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@60704c, started on Thu Mar 14 22:27:17 KST 2024
NetworkClient.close
close url = http://www.naver.com

빈으로 생성 될 클래스에서 의존 관계 주입 후 실행 될 콜백 함수일 경우 @PostContruct를 명시해주면 해당 메서드가 실행 된다.
빈 소멸 전에 호출 할 메서드는 @PreDestroy를 명시해준다. 그러면 빈 소멸 전에 해당 메서드가 실행 된다.

정리

빈 어노테이션에 iniMethod, destroyMethod를 사용하는 것 보단 요즘 추세는 @PostConstruct, @PreDestory를 사용한다(스프링에서도 권장하는 방법이다!).
하지만 유일한 단점으로 외부 라이브러리에는 적용하지 못한다. 따라서 외부 라이브러리를 초기화, 종료 할때만 initMethod, destroyMethod를 사용하자!

profile
인생은 IT 노가다

0개의 댓글