개발일기장

Spring 공부 05. Bean Life Cycle 본문

Spring Boot

Spring 공부 05. Bean Life Cycle

게슬 2023. 7. 10. 21:33
728x90

1. Spring Bean의 생성 ~ 소멸

1. Spring Bean 은 객체 생성 이후 의존관계를 주입함.

2. 주입이 다 끝나고 나서야 필요한 데이터를 사용 할 수 있음

3. 초기화? 이미 내부에 주입을 해서 setting이 완료된 상태임

4. Bean의 시작, 종료 시점에 callback을 줌

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

public class NetworkClient {

    private String url;

    public NetworkClient(){
        System.out.println("생성자 호출, url = " + url);
        call("초기화 연결 메시지");
    }


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

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

이런 Class가 있고. 

 

        @Bean
        public NetworkClient networkClient(){
		//1. 이미 여기서 객체 생성이 다 끝남
            NetworkClient networkClient = new NetworkClient();
            
		//2. 이거는 이후 이야기
            networkClient.setUrl("http://hello!!");
            return networkClient;
        }

이렇게 Bean을 등록 했다고 치자.

 

외부에서 해당 Bean을 호출 할 때 Constructor에서 call하는 url값은 null이 될 것임


2. 초기화 콜백, 소멸 콜백 

이거는 3가지를 지원해줌

인터페이스, Method, Annotation.

2-1. 인터페이스

public class NetworkClient implements InitializingBean, DisposableBean {
....

    @Override
    public void destroy() throws Exception {
        .....
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        .....
    }
....
}

이렇게 2개의 interface를 상속받고 afterPropertiessSet(생성시점), destroy(소멸시점)에 호출시킬수 있다

그런대 이 방법은 외부 Library(Spring)에 의존적인 소스코드가 됨 + 지금은 잘 사용하지 않는 방식

 

2-2. Method

    public void init(){
        ...
    }

    public void close(){
        ...
    }
    
    
    ...
    
            @Bean(initMethod = "init", destroyMethod = "close")
        public NetworkClient networkClient(){
            ....
        }

이렇게 Method를 만든 다음에 Bean에 등록을 해주면 된다. initMethod와 destoryMethod에 등록된 method이름을 생성 / 소멸 시점에 호출해줌.

Spring에 의존적이지 않기때문에 외부 라이브러리에 적용이가능함

2-3. Annotation

    @PostConstruct
    public void connect(){
        ...
    }


    @PreDestroy//이거 2개는 자바 표준임.. 다른 컨테이너에서도 잘 동작을 함.
    public void disconnect(){
        ...
    }

그냥 이거 쓰셈 @PostConstruct, @PreDestroy를 호출하면 생성시점, 종료직전에 호출해서 정리를 해준다. 

 

728x90
Comments