빈 생명주기 콜백 - 애너테이션(@PostConstruct, @PreDestory)

2023. 8. 24. 01:24Spring/[inflearn]스프링 핵심 원리 - 기본편

-> 스프링에는 3가지 방법의 빈 생명주기 콜백을 지원한다.

1. 인터페이스(InitializingBean, DisposableBean)

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

3. @PostConstruct, @PreDestroy 애너테이션

 

애너테이션(@PostConstruct, @PreDestory) 

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class NetworkClient{
    private String url; // 접속할 서버의 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() throws Exception { // 의존관계 주입이 끝나면 호출 -> 초기화
        System.out.println("NetworkClient.init");
        connect();
        call("초기화 메시지");
    }

    @PreDestroy
    public void close() throws Exception { // 빈이 종료될 때 호출 -> 소멸
        System.out.println("NetworkClient.close");
        disconnect();
    }


}

-> 테스트 코드

public class BeanLifeCycle {
    @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://lifecycle.com");
            return networkClient;
        }
    }
}

-> 결과

 

@PostConstruct, @PreDestory 특징

-> 최신 스프링에서 권장하는 방법이다.

-> 애너테이션만 붙이면 된다.

-> @PostConstruct와 @PreDestroy의 패키지를 보면 javax인데 이것은 스프링에 종속적인 기술이 아닌 자바 표준이다. 따라서 스프링이 아닌 다른 컨테이너에서도 동작한다.

-> 코드를 직접 작성하기 때문에 외부 라이브러리에 적용하지 못한다.

 

 

☆ 참고

[인프런]스프링 핵심 원리 - 기본편