본문 바로가기
개발하자/Spring

SPRING bean life cycle

by ulqaef 2020. 3. 25.
728x90

 

스프링컨테이너는 빈 객체를 생성하고 프로퍼티를 할당하고 초기화를 수행하고 사용이 끝나면 소멸시키는 과정을 관리하게 된다.

 

과정은 다음과 같다. 

 

빈 라이프사이클

 

Bean객체를 생성한 후 Bean Property 설정한 뒤에 BeanNameAware.setBeanName()메서드를 호출하게 되는데

생성된 Bean이 BeanNameAware인터페이스를 구현하고 있을 경우 setBeanName()메서드를 호출하고 

ApplicationContextAware인터페이스를 구현하고 있는 경우 setApplicationContext()메서드를 호출한다.

 

 

위 그림의 전체적인 흐름을 보게되면 [객체생성/프로퍼티설정 -> 초기화 -> 사용 -> 소멸] 단계를 거치게 된다.

 

빈의 초기화와 소멸 방법은 각각 세 가지가 존재한다. 각 방식이 쌍을 이루어 사용된다.

 

1. 

InitializingBean인터페이스와 DisposableBean인터페이스

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

public interface DisposableBean {
	void destroy() throws Exception;
}

스프링 컨테이너는 생성한 빈 객체가 InitializingBean 인터페이스를 구현하고 있으면 InitializingBean인터페이스로 정의되어 있는 afterPropertiesSet()메서드를 호출한다. 따라서 스프링 빈 객체가 정상적으로 동작하기 위해 객체 생성 이외의 추가적인 초기화 과정이 필요하다면 InitializingBean인터페이스를 상속받고 afterPropertiesSet()메서에서 초기화 작업을 수행하면 된다. 

 

스프링 컨테이너가 종료될 때 빈 객체가 알맞은 처리가 필요하다면 DisposableBean인터페이스를 상속받고 destroy()메서드를 override해서 재정의 해주면 된다.

public class SimpleExample implements InitilizingBean, DisposableBean {
	
    @Override
    public void afterPropertiesSet() throws Exception {
      /* 초기화 과정에서 새롭게 설정을 해줘야 한다면 override를 해주어 재정의한다. */	
    }
    
    @Override
    public void destroy() throws Exception {
      /* 소멸 단계에 무언가 새롭게 설정해주어야 한다면 override를 해주어 재정의한다. */
    }
  
    /*
    *
    *    중략
    *
    */
}

 

2. @PostConstruct어노테이션과 @PreDestroy어노테이션

InitializingBean, DisposableBean인터페이스를 구현하는 것 말고도 @PostConstrucotr, @PreDestroy 어노테이션을 사용할 수 있는데 각각  초기화와 소멸단계에 실행할 메서드에 적용해주면 된다.

 

import javax.annotation.PostConstructor
import javax.annotation.PreDestroy

public class ConnPool {
	
    @PostConstruct
    public void initPool() {
    /* Initalize the connection pool */
    }
    
    @PreDestroy
    public void destroyPool() {
    /* destroy the connection pool */
    }
}

 

※주의

@PostConstruct, @PreDestroy어노테이션은 JSR250에 정의되어 있기 때문에 CommonAnnotationBeanPostProcessor전처리기를 스프링 빈으로 등록해주어야 한다.

<context:anntation-config> 태그를 사용하면 CommonAnnotationBeanPostProcessor가 빈으로 등록된다.

 

3. 커스텀 init메서드와 커스텀 destroy메서드

외부 라이브러리의 클래스를 이용하여 init()메서드와 destroy()메서드를 정의할 수 있다. 

XML설정을 사용한다면 init-method속성과 destroy-method속성을 사용해서 초기화 및 소멸과정에 사용할 메서드의 이름을 지정하면 된다.

<bean id="pool3" class="com.spring.example.SimpleExample" 
	init-method="init" destroy-method="destroy" />

자바 기반 설정을 사용한다면 @Bean어노테이션의 initMethod속성과 destroyMethod속성을 사용하면 된다.

@Bean(initMethod="init", destroymethod="destroy")
public SimpleExample simpleExample() {
	return new simpleExample();
}

==========================================================

 

 

 

1. InitializingBean인터페이스와 DisposableBean인터페이스 예제

 

[SimpleExample.class]

package com.spring.example;

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

public class SimpleExample implements InitializingBean, DisposableBean {

    @Override
    public void destroy() throws Exception {
        System.out.println("Disposable인터페이스의 destroy를 override하여 재정의한다.");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean인터페이스의 afterPropertiesSet을 override하여 재정의한다.");
    }
}

 

[MainExample.class]

package com.spring.example;

import org.springframework.context.support.GenericXmlApplicationContext;

public class MainExample {

    public static void main(String[] args) {
        GenericXmlApplicationContext context = new GenericXmlApplicationContext();
        context.refresh();
        context.load("classpath:META-INF/spring/root-context.xml");
        SimpleExample se = context.getBean("simpleBean", SimpleExample.class);
        
        context.close();
    }

}

 

[root-context.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	

	<bean id="simpleExample" class="com.spring.example.SimpleExample" />
</beans>

==========================================================

 

 

2. @PostConstruct어노테이션과 @PreDestroy어노테이션 예제

[SimpleExample.class]

package com.spring.example;

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

public class SimpleExample {
    
    @PostConstruct
    public void init() throws Exception {
        System.out.println("BEAN INFO : init()메소드 호출");
    }
    
    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("BEAN INFO : destroy()메서드 호출");
    }
}

 

[root-context.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<!-- Root Context: defines shared resources visible to all other web components -->
    <context:annotation-config/>
    	
	<bean id="simpleExample" class="com.spring.example.SimpleExample" />
</beans>

==========================================================

 

 

3. 커스텀 init메서드와 커스텀 destroy메서드 예제

 

[SimpleExample.class]

package com.spring.example;

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

public class SimpleExample {
    
    @PostConstruct
    public void init() throws Exception {
        System.out.println("BEAN INFO : init()메소드 호출, 객체생성 및 초기화");
    }
    
    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("BEAN INFO : destroy()메서드 호출, 객체 소멸");
    }
}

[root-context.xml]

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<!-- Root Context: defines shared resources visible to all other web components -->    	
	<bean id="simpleExample" class="com.spring.example.SimpleExample" 
		init-method="init" destroy-method="destroy"/>
</beans>

728x90
반응형

댓글


`