개발/Spring Framework

[Spring Framework] 생명 주기

백괴 2020. 9. 23. 18:25

스프링 컨테이너의 생명 주기는 위 그림과 같이 생명, 사용, 소멸로 나눌 수 있습니다.

  1. 생성 : GenericXmlApplicationContext 등을 통해 스프링 컨테이너를 생성합니다. 동시에 Bean 객체 또한 생성됩니다.
  2. 사용 : getBean()을 통해 Bean 객체를 이용합니다.
  3. 소멸 : close()를 통해 스프링 컨테이너를 종료합니다.

이러한 생성 시점과 소멸 시점은 두 가지 방법을 통해 사용할 수 있습니다. 두 가지 방법 중, 어느 것을 사용하셔도 무방합니다.

  • initializingBeanDisposable 인터페이스 사용
  • Bean 객체에 init-methoddestroy-method 속성 추가 후 해당 메소드에 구현

 

1. 인터페이스 사용

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

//인터페이스 불러오기
public class Home implements InitializingBean, DisposableBean {
	
	public String myHome;
	
	public void setMyHome(String myHome) {
		this.myHome = myHome;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("Bean 객체 생성");
	}
	
	@Override
	public void destroy() throws Exception {
		System.out.println("Bean 객체 소멸");
	}

}

객체에 implements 키워드를 통해 initializingBean과 Disposable 인터페이스를 입력하여 불러올 수 있습니다.

 

implements 키워드를 입력한 다음, Add unimplemented methods를 클릭하면 자동으로 afterPropertiesSet, destroy 메소드가 생성됩니다.

각각 Bean 객체가 생성될 때, 소멸될 때 실행되는 매소드이며, 해당 시점에 실행 할 코드를 입력해주시면 됩니다.

 

 

2. 메소드 속성 사용

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
 		http://www.springframework.org/schema/beans/spring-beans.xsd
 		http://www.springframework.org/schema/context
 		http://www.springframework.org/schema/context/spring-context.xsd">
        
    <context:annotation-config />
    
    <bean id="home" class="Home"
        	init-method="initMethod" destroy-method="destroyMethod">
            <!-- 메소드 속성 추가 -->
    	<property name="myHome" value="성남시"/>
    </bean>

</beans>

환경설정 파일의 Bean 객체에 init-method(생성), destroy-method(소멸) 속성을 사용하여 각각 시점에 실행하고자 하는 메소드 이름을 써주시면 됩니다.

 

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

public class Home implements InitializingBean, DisposableBean {
	
	public String myHome;
	
	public void setMyHome(String myHome) {
		this.myHome = myHome;
	}

	@Override
	public void initMethod() {
		System.out.println("Bean 객체 생성");
	}
	
	@Override
	public void destroyMethod() {
		System.out.println("Bean 객체 소멸");
	}

}

Home 객체의 각각 해당 메소드에는, 위의 코드와 같이 각 시점마다 실행하고자 하는 코드를 입력해 주시면 되겠습니다.