본문 바로가기

Spring

Spring Bean LifeCycle 스프링 빈 생명주기

1.  Spring Bean 라이프 사이클

스프링 빈은 다음과 같은 생명주기를 갖는다.

 

1. XML 설정 혹은 ComponetScan 을 통해 빈 정의를 스캔하여 등록

2. 등록된 빈들의 인스턴스 생성

3. 의존관계 주입 

4. Aware Inteface 가 구현되어 있다면 Aware Interface 콜

[BeanNameAware ->  BeanClassLoaderAware -> ApplicationContextAware]

5. 초기화 

6. 소멸

 

여기서 포스팅으로 다룰만한 내용은 Aware Interface 와 초기화 소멸 단계인데,

생명주기에서 상세히 다룰 내용이 아닌 Aware Interfcae 는 다른 포스팅에서 작성하도록 하고

 

초기화와 소멸 단계에 대해 상세히 알아보자.

 

2. Bean Initialize 빈 초기화 콜백

스프링은 여러가지 방법의 빈 초기화 방법을 제공한다.

 

가.  @PostConstruct

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }

어노테이션만 붙여주면, 알아서 수행된다.

프레임워크에 대해 생기는 의존성이  낮고 사용방법이 간단해 추천되는 방식이다.

다만 직접 해당 메서드에 어노테이션을 붙여주어야 하기 때문에 외부 라이브러리에 사용이 불가능하다.

 

나. InitializingBean Interface afterPropertiesSet()

import org.springframework.beans.factory.InitializingBean;

public class TestBean implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean afterPropertiesSet");
    }
}

별 다른 장점이 없는 방법.

스프링에서 제공하는 인터페이스를 구현해야하기 때문에, 스프링 컨테이너와 강결합이 발생한다.

또한 구현 메서드 명도 바꿀수도 없다. 가장 유연하지 못한 방법.

 

다. Custom Init method 호출

public class TestBean {
    public void customInitMethod() {
        System.out.println("Custom Init Method Called By @Bean(initMethod)");
    }
}

@Configuration
public class Config {
	
    @Bean(initMethod = "customInitMethod")
    public TestBean testBean() {
        return new TestBean();
    }
}

어노테이션 방법에 비하여 조금 불편하긴 하나,

메서드 명도 자유롭고, 빈으로 등록될 객체 자체에는 어노테이션으로 인한 논리적인 결합 조차도 존재하지 않는다.

또한 외부 라이브러리에도 사용가능하다는 장점이 있다.

굳이 단점을 찾자면 설정 클래스를 보지 않는다면 초기화 과정을 이해할 수 없다는 정도.. 

주로 어노테이션 방식을 이용하고, 외부 라이브러리에 사용시 해당 방법을 사용하면 된다.

 

3. Bean Destroy 빈 소멸 콜백

빈의 소멸 콜백도 알아보자. 소멸은 해당하는 초기화 방법과 장/단점이 동일하니 따로 기술하지 않는다.

 

가. @PreDestroy Annotation

    @PreDestroy
    public void close() {
        System.out.println("PreDestroy");
    }

 

나. DisposalBean Interface destroy()

import org.springframework.beans.factory.DisposableBean;

public class TestBean implements DisposableBean, InitializingBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposalBean destroy");
    }
}

 

다. Custom destroy method 호출

public class TestBean {
    public void customDestroyMethod() {
        System.out.println("Custom Init Method Called By @Bean(destroyMethod)");
    }
}

@Configuration
public class Config {
	
    @Bean(destroyMethod = "customDestroyMethod")
    public TestBean testBean() {
        return new TestBean();
    }
}

 

 

4. 각 콜백의  실행 순서

여러가지 생명주기 콜백을 알아보았다.

그럼 빈 생명주기 내에서 각각의 콜백은 어떤 순서로 동작할까?

 

코드를 통해 알아보자

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

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class TestBean implements DisposableBean, InitializingBean {

    static {
        System.out.println("static");
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }

    @PreDestroy
    public void close() {
        System.out.println("PreDestroy");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposalBean destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean afterPropertiesSet");
    }

    public void customInitMethod() {
        System.out.println("Custom Init Method Called By @Bean(initMethod)");
    }

    public void customDestroyMethod() {
        System.out.println("Custom Init Method Called By @Bean(destroyMethod)");
    }
}


@Configuration
public class Config {
	
    @Bean(initMethod = "customInitMethod", destroyMethod = "customDestroyMethod")
    public TestBean testBean() {
        return new TestBean();
    }
}

 

실행 결과는 다음과 같다.

static
PostConstruct
InitializingBean afterPropertiesSet
Custom Init Method Called By @Bean(initMethod)
PreDestroy
DesposalBean destroy
Custom Destroy Method Called By @Bean(destroyMethod)

 

 

 

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-nature