Spring container Lifecycle

2020. 11. 18. 18:04☕️ Java

Spring Container 생애주기

 

- Spring Container: 프로젝트 내의 여러 클래스 파일들을 bean이라는 형태로 xml에 모아둔 것

 

  • 스프링 컨테이너 초기화(생성) : Bean 객체 생성 및 주입
  • 스프링 컨테이너 종료 : 스프링 컨테이너가 메모리에서 소멸 ( Bean 객체 소멸 )

Spring Lifecycle 확인하는 2가지 방법

1) <Interface> InitailizingBean, DisposableBean

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

public class BookDao implements InitializingBean, DisposableBean {
	
    ...
    ...
    
    
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("빈(Bean)객체 생성 단계");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("빈(Bean)객체 소멸 단계");
	}
	
}
  • InitializingBean, DisposableBean 두 인터페이스를 상속받는다
  • InitializingBean, DisposableBean 인터페이스의 메서드를 정의해야한다.
  • 두 인터페이스는, 해당 BookDao 클래스가 spring container에서 생성될 때 동작하여 명령어를 출력한다. ("빈 객체 생성 단계 / 빈 객체 소멸 단계")

 

 

2) init-method="initMethod" destroy-method="destroyMethod"

위 방법은 xml 파일의 Bean 객체에 속성을 부여한다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans">
    
    ...
    ...
    
	<bean id="bookRegisterService" class="service.BookRegisterService" 
	init-method="initMethod" destroy-method="destroyMethod"/>

    ...
    

</beans>
  • <bean /> 태그내에 inti-method와 destroy-method 속성 정의
  • 해당 BookRegisterService 클래스 내부엔 각각 initMethod, destroyMethod를 정의

- BookRegisterService class

public class BookRegisterService{

	///
    
	public void initMethod() {
		System.out.println("BookRegisterService 빈(Bean)객체 생성 단계");
	}
	
	public void destroyMethod() {
		System.out.println("BookRegisterService 빈(Bean)객체 소멸 단계");
	}

}
  • bean 객체 내부에서 정의한대로 initMethod(), destroyMethod()를 선언

 

 

출처: 자바 스프링 프레임워크(renew ver.) - 신입 프로그래머를 위한 강좌