티스토리 뷰

bean 객체 생성 시 초기화 작업을 각 인터페이스를 구현받아 사용할 수 있다.

 

1. init-method : 커스텀 초기화 메서드


2. destroy-method : 커스텀 소멸 메서드


3. BeanNameAware 인터페이스
=> 빈 객체가 자기 자신의 이름을 알아야 하는 경우에 사용
=> 빈 클래스가 BeanNameAware 를 구현한 경우
컨테이너는 setBeanName( ) 메서드를 호출하여 빈 객체의 이름을 전달
=> setBeanName(String arg) : 객체가 생성될 때 해당 객체 빈 의 id( 혹은 name) 값을 전달 받는 메서드


◎LifeBean.java

package test.exam06;

public interface LifeBean {
	void lifeMethod();
}

◎LifeBeanImpl.java

package test.exam06;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;

public class LifeBeanImpl implements LifeBean, BeanNameAware, BeanFactoryAware {

	private String beanName;  //설정 파일에서 설정한 Bean의 id를 저장할 변수
	private BeanFactory beanFactory; //스프링의 beanFactory 구현체를 저장할 변수
	
	
	public LifeBeanImpl() {
		// TODO Auto-generated constructor stub
	}

	
	public void begin() {
		System.out.println("사용자 초기화 메서드");
	}
	
	public void end() {
		System.out.println("사용자 소멸 메서드");
	}
	
	//Bean 객체가 자기 자신의 이름을 알아야 할 경우에 사용
	//객체가 생성될 때 해당 객체의 id값을 전달(주입) 받는 메서드
	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	//객체가 생성될 때 스프링의 BeanFactory를 전달받는 메서드
	@Override
	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	@Override
	public void lifeMethod() {
		System.out.println("비지니스 로직이 수행 중입니다.");
		System.out.println("beanName : " + beanName);
	}

}

◎life.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean name = "lifeBean" class = "test.exam06.LifeBeanImpl" init-method = "begin" destroy-method = "end">
	
	</bean>

</beans>

◎Main

package test.exam06;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext("/src/test/exam06/life.xml");
		LifeBean bean = (LifeBean)context.getBean("lifeBean");
		
		bean.lifeMethod();
	}

}

위와 같이 init-method, destroy-method에 임의의 메서드를 명시하여, bean 객체 생성&파괴 시 자동 호출하게끔 할 수 있다.

 

물론, 임의의 메서드가 아닌, Spring에서 미리 구현해놓은 메서드를 사용할 수도 있다.

 

- InitializingBean 인터페이스
=> spring framework 에서 제공하는 초기화 메소드
=> 객체를 생성하고 프로퍼티를 초기화하고 , 컨테이너 관련 설정을 완료한 뒤에 호출되는 메서드


- DisposableBean 인터페이스
=> spring framework 에서 제공하는 소멸 메소드
=> 빈 객체를 컨테이너에서 제거하기 전에 호출 하여 빈 객체가 자원을 반납할 수 있도록 함

Comments