[Spring] 기본편 08. 빈 생명주기 콜백
이 글은 스프링 [핵심원리 - 기본편]을 듣고 정리한 내용입니다
📌 빈 생명주기 콜백 시작
- 
데이터베이스 커넥션 풀이나 네트워크 소켓처럼 애플리케이션 시작 지점에 필요한 연결을 미리 해두고, 애플리케이션 종료 시점에 연결을 모두 종료하는 작업을 진행하려면, 객체의 초기화와 종료 작업이 필요하다. 
- 
스프링을 통해 초기화 작업과 종료 작업 하는 예시 
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 +", messge = "+message);
    }
    //서비스 종료시 호출
    public void disconnect(){
        System.out.println("close: "+ url);
    }
}
- 스프링의 환경설정과 실행
package hello.core.lifecycle;
import java.lang.annotation.Annotation;
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;
        }
    }
}
- 출력 결과
  
- 객체를 생성하는 단계에는 당연히 url이 없다.
- 객체를 생성한 다음에 외부에서 수정자 주입을 통해 setUrl()이 호출되어야 url이 존재하게 된다.
스프링 빈의 라이프 사이클
- 객체 생성 -> 의존관계 주입
- 의존관계 주입이 오나료되고 난후 초기화 작업을 해야한다.
- 스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해 초기화 시점을 알려주는 다양한 기능을 제공한다.
- 스프링은 스프링 컨테이너가 종료되기 직전에 소멸 콜백을 준다.
스프링 빈의 이벤트 라이프 사이클
- 스프링 컨테이너 생성 -> 스프링 빈 생성 -> 의존관계 주입 -> 초기화 콜백 -> 사용 -> 소멸 전 콜백 -> 스프링 종료
*참고
- 객체의 생성과 초기화를 분리하자.
- 생성자는 필수 정보(파라미터)를 받고, 메모리를 할당해서 객체를 생성하는 책임을 가진다.
- 초기화는 생성된 값들을 활용해서 외부 커넥션을 연결하는 등 무거운 동작을 수행한다.
스프링에서 지원하는 빈 생명주기 콜백 방식 3가지
- 인터페이스(InitializingBean, DisposableBean)
- 설정 정보에 초기화 메서드, 종료 메서드 지정
- @PostConstruct, @PreDestory 어노테이션 지원
📌 인터페이스 InitializingBean, DisposableBean
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 +", messge = "+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 {
        System.out.println("NetworkClient.destroy");
        disconnect();
    }
}- InitializingBean은- afterPropoertiesSet()메서드로 초기화를 지원한다.
- DisposableBean은- destroy()메서드로 소멸을 지원한다.
- 출력 결과
  
- 결과를 보면, 초기화 메서드가 주입 완료 후에 적절하게 호출 되었다.
- 스프링 컨테이너의 종료가 호출되자 소멸 메서드가 호출 된 것도 확인 할 수 있다.
초기화, 소멸 인터페이스의 단점
- 이 인터페이스는 스프링 전용 인터페이스이다. 그러므로, 해당 코드가 스프링 전용 인터페이스에 의존한다.
- 초기화, 소멸 메서드의 이름을 변경할 수 없다.
- 내가 코드를 고칠 수 없는 외부 라이브러리에 적용할 수 없다.
- 인터페이스를 사용하는 초기화, 종료 방법은 초창기(2003년)에 나온 방법들이다.
- 지금은 더 나은 방법들이 있어서 거의 사용하지 않는다.
📌 빈 등록 초기화, 소멸 메서드 지정
- 
설정 정보에 @Bean(initMethod = "init", destroyMethod="close") 처럼 초기화, 소멸 메서드를 지정할 수 있다. 
- 
init, close 함수 작성 
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 +", messge = "+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();
    }
}
- 설정정보에 초기화, 소멸 메서드 지정
@Configuration
    static class LifeCycleConfig {
        @Bean(initMethod = "init", destroyMethod = "close") //init, close 등록
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }- 출력 결과
  
- 설정 정보 사용 특징- 메서드 이름 자유롭게 설정 가능
- 스프리 빈이 스프링 코드에 의존하지 않는다.
- 코드를 고칠 수 없는 외부 라이브러리에도 초기화,종료 메서드를 적용 할 수 있다.
 
*종료 메서드 추론
@Bean의 destoryedMethod속성의 특별한 기능
@Bean의 destryMethod는 디폴트 값이(inferred)(추론)으로 등록되어 있다.- 라이브러리는 대부분
close,shutdown이라는 이름의 종료 메서드를 사용하는데, 위의 추론 기능은close,shutdown이라는 이름의 메서드를 자동으로 호출해준다. (다른 이름이면 안됨.)- 그러므로, 직접 스프링 빈 등록 방식을 이용하면, 종료 메서드는 따로 적어주지 않아도 된다.
📌 어노테이션 @PostConstruct, @PreDestroy
- 결론적으로 이 방법을 쓰면 된다. (스프링에서도 권고하고 있음)
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 +", messge = "+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만 붙인다.
  @Configuration
    static class LifeCycleConfig {
        @Bean
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }- 
출력 결과를 보면, 잘 호출된다. 
  
- 
@PostConstruct,@PreDestory이 두 어노테이션을 사용하면 가장 편리하게 초기화와 종료를 실행 할 수 있다.
- 
@PostConstrcut, @PreDestory 어노테이션 특징 - 최신 스프링에서 가장 권장하는 방법이다.
- 패키지를 보면 import javax.annotation.PostConstruct;이다. 스프링 종속적인 기술이 아니라 자바 표준이므로, 스프링이 아닌 다른 컨테이너에서도 동작한다.
- But, 외부 라이브러리에는 적용 못한다.
 
🌱 정리
- @PostConstruct, @PreDestory 어노테이션을 사용하자
- 코드를 고칠 수 없는 외부 라이브러리를 초기화, 종료 해야하면 @Bean의initMethod,destroyMethod를 사용하자.
 
Author And Source
이 문제에 관하여([Spring] 기본편 08. 빈 생명주기 콜백), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@somyeong0623/Spring-기본편-08.-빈-생명주기-콜백저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)