본문 바로가기

java/spring

[spring] 스프링 컨테이너의 생명주기

주제
스프링 컨테이너의 생명주기, 각 생명주기에 작동가능한 메소드 

 

 

스프링 컨테이너의 생명주기


 스프링 컨테이너의 생명주기는 빈 객체의 생명주기와 동일하다.

 

생성

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appCtx.xml");

위처럼 설정파일 인스턴스를 호출하는 시점에 스프링 컨테이너가 초기화되며, 빈 객체 생성 및 메모리 할당이 이뤄진다.

 

ctx.getBean("registerService", registerService.class);

getBean은 컨테이너에서 이미 생성된 빈을 가져다 쓰는 것에 불과하다.

 

ctx.close();

위처럼 close 메소드를 호출하면, 스프링 컨테이너가 종료되며,빈 객체 소멸과 메모리 해제가 이뤄진다.

 

생명주기 메소드 구현


빈 객체 생성이나 소멸 등의 생명주기 단계 전후에서 작업을 추가할 수 있는 메소드를 생명주기 메소드라 한다. 이는 DB접속이나 네트워크 자원 등 빈의 초기화 및 소멸 단계에서 필요한 작업을 세팅할 때 용이하다.

방법은 인터페이스 구현 방식과 스프링 컨테이너 방식 두 가지가 존재한다.

두 방식은 함께 사용될 수도 있다.

( 단, 인터페이스 방식과 함께 설정할 시 스프링 컨테이너에서 설정한 생명주기 메소드가 더 늦게 실행된다. )

인터페이스 구현 방식

public class RegisterService implements InitializingBean, DisposableBean {

	public RegisterService() {
		System.out.println("register 서비스 시작");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("빈 초기화");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("빈 소멸");
	}
}
  • 인터페이스 구현 - InitializingBean, DisposableBean
  • initializingBean  - afterPropertiesSet  메소드 | 생성자 함수 실행 이후  빈 생성 시점에 실행
  • DisposableBean- destroy 메소드 | ctx.close()로 빈이 소멸한 이후 시점에 실행

 

스프링 컨테이너 방식

컨테이너 설정 파일xml에서 빈 태그에 빈 생성 시 실행될 메소드와 빈 해제 시 실행될 메소드를 각각 init-method 속성과 destroy-method 속성으로 지정하면 된다.

인터페이스 방식과 함께 사용한 예시를 보자.

 

xml 설정

<bean id="registerService" class="testPjt11.service.RegisterService" 
init-method="initBeanEX1" destroy-method="destroyBeanEX1" />

 

  • 빈 생성 시점 메소드로 initBeanEX1를 설정함(이름은 자유)
  • 빈 생성 시점 메소드로 destroyBeanEX1를 설정함(이름은 자유)

 

class 파일

package testPjt11.service;

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

import testPjt11.service.entity.Character;

public class RegisterService implements InitializingBean, DisposableBean {

	public RegisterService() {
		System.out.println("register 서비스 시작(생성자 함수 호출)");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("인터페이스로 빈 초기화 메소드");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("인터페이스로 빈 소멸 메소드");
	}
	
	private void initBeanEX1() {
		System.out.println("xml에서 빈 초기화 메소드");
	}
	
	private void destroyBeanEX1 () {
		System.out.println("xml에서 빈 해제 메소드");
	}
}

스프링 컨텍스트로 구현한 생명주기 메소드는 private라도 실행된다.

 

실행해보면 콘솔에 다음 순서대로 출력된다.

register 서비스 시작(생성자 함수 호출)

인터페이스로 빈 초기화 메소드

xml에서 빈 초기화 메소드

인터페이스로 빈 소멸 메소드

xml에서 빈 해제 메소드