본문 바로가기
Spring

Spring Lifecycle Callback

by 스르나 2021. 3. 20.

 

스프링 빈의 생성 라이프사이클 콜백 메소드의 종류와 만드는 방법을 알아보자.

 

1. 생성 콜백

우선 생성 콜백이 있다. 생성 콜백은 스프링 빈이 생성 될때 호출되는 메소드이다.

 

생성 콜백을 만드는 방법 3가지가 있다.

 

1.InitializingBean interface 상속

2.XML 혹은 @Configuration 에서 Bean 속성 설정

3.@PostConstruct 어노테이션 사용 <-추천 방식

 

1-1 InitializingBean interface 상속

우선 1번 방법부터 보자면 org.springframework.beans.factory.InitializingBean interface를 상속 받아서 void afterPropertiesSet() throws Exception;를 구현 하는 방식이다.

 

package org.springframework.beans.factory;

public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}

InitializingBean은 위와같이 메소드가 1개있는 인터페이스이다.

 

@Service
public class UserService implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("UserService Bean init!!!");
    }
}

위 인터페이스를 상속받아서 구현을 하면 자동으로 Bean 생성시 호출이 된다.

 

이방식은 스프링 공식분서에서 추천을 하지 않는다. 이유는 스프링에서 추구하는 POJO 개념과 다르게 클래스가 무거워 지기 때문이다.(스프링 코드와 강하게 결합되는 것을 가급적 피하는것이 좋다.)

 

1-2 XML 혹은 @Configuration 에서 Bean 속성 설정

그 다음으로 Bean의 속성을 설정하는 방식이다.

 

@Configuration
public class BeanConfig {
    
    @Bean(initMethod = "init")
    public BeanService beanService(){
        return new BeanService();
    }
}
public class BeanService {

    public void init(){
        System.out.println("BeanService init method called!!!");
    }
}

방식은 위와 같이 Bean 클래스에 init callback 메소드로 사용할 메소드를 구현한뒤에 설정에서 initMethod 속성을 추가해주면 된다.(initMethod의 문자열과 메소드 이름이 같아야 한다.)

 

이방식의 장점은 이름을 설정하는데 있다. 흔히 클래스의 생성 콜백, 소멸 콜백 메소드는 init,dispose 같은 이름으로 생성한다. 그렇기 때문에 이런 이름을 이용하는 것이 일반적이다. Bean 속성 설정방식은 이런 자주 사용되는 이름(예측 가능한 이름)을 이용할 수 있다는 장점이 있다. (Clean Code에서도 메소드의 이름만 읽고 어떻게 작동하는지 알 수 있으면 좋다고 한다.)

 

1-3 @PostConstruct 어노테이션 사용

가장 추천하는 방식이라고 스프링 DOC에 써있다. 사용 방식도 콜백 메소드로 사용할 메소드에 어노테이션을 붙이기만 하면 된다.

 

@Service
public class UserService  {
    @PostConstruct
    public void init(){
        System.out.println("@PostConstruct called!!!");
    }
}

@PostConstruct 어노테이션은 스프링 어노테이션이 아니기 때문에 스프링과 의존이 떨어져있기 때문에 추천한다고 한다. javax.annotation.PostConstruct는 jsr-250 api에 있는 것이다.

 

2. 소멸 콜백

소멸 콜백은 스프링 빈이 소멸할 때 호출되는 메소드이다.

 

소멸 콜백 또한 생성 콜백과 마찬가지로 3가지 생성 방식이 있고 각각 생성 콜백과 같은 방식이다. 추가적인 설명을 생성 콜백과 동일하니 사용 방법만 적어 놓겠다.

 

1. DisposableBean interface 상속

2. XML 혹은 @Configuration 에서 Bean 속성 설정

3. @PreDestroy 어노테이션 사용 <- 추천 방식

 

2-1 DisposableBean interface 상속

 

@Service
public class UserService implements DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("UserService Bean Dispose!!!");
    }
}

 

2-2 XML 혹은 @Configuration 에서 Bean 속성 설정

@Configuration
public class BeanConfig {

    @Bean(initMethod = "init",destroyMethod = "")
    public BeanService beanService(){
        return new BeanService();
    }
}

 

public class BeanService {

    public void init(){
        System.out.println("BeanService init method called!!!");
    }
    
    public void dispose(){
        System.out.println("BeanService dispose method called!!!");
    }
}

 

2-3 @PreDestroy 어노테이션 사용

@Service
public class UserService  {    
    @PreDestroy
    public void dispose(){
        System.out.println("@PreDestroy called!!!");
    }
}

 

'Spring' 카테고리의 다른 글

Spring Jpa 테스트 H2, TestEntityManager  (0) 2022.01.20
@WebMvcTest  (0) 2021.07.01
Spring 단위테스트 -2 Data  (0) 2021.02.28
Spring 단위테스트 - 1  (0) 2021.02.28
InMemory-H2  (0) 2021.02.23