스프링 핵심 원리/빈 생명주기 콜백

애노테이션 @PostConstruct , @PreDestory

jeongdalma 2021. 1. 2. 02:47

Class

package hello.core.lifeCycle;

// javax는 자바에서 공식적으로 지원하는 것들
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() throws Exception {
        connect();
        call("초기화 연결 메시지");
    }

    // 서버가 종료 될 때
    @PreDestroy
    public void close() throws Exception {
        System.out.println("destory");
        disconnect();
    }
}

Test

public class BeanLifeCycleTest {

    @Test
    public void lifeCycleTest(){
        // 스프링 컨테이너 생성
        AnnotationConfigApplicationContext ac =
                new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        NetworkClient bean = 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;
        }
    }
}

출력

생성자 호출 , url = null
Connect : http://hello-spring.dev
Call : http://hello-spring.dev message : 초기화 연결 메시지
destory
close : http://hello-spring.dev

 

특징

  • 최신 스프링에서 가장 권장하는 방법이다.
  • 스프링에 종속적인 기술이 아니라 JSR-250이라는 자바 표준이다.따라서 스프링이 아닌 다른 컨테이너에서도 동작한다.
  • 컴포넌트 스캔(자동 빈 등록)과 잘 어울린다.
  • 유일한 단점은 외부 라이브러리에는 적용하지 못한다는 것이다. 외부 라이브러리를 초기화 , 종료 해야하면 @Bean의 기능을 사용하자

 

 

 

 

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

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다. 초급 프레임워크 및 라이브러리 웹 개발 서버 개발 Back-End Spring 객체지향 온

www.inflearn.com