티스토리 뷰

bean 객체가 필요한 객체를 스프링 컨테이너 (BeanFactory 나 ApplicationContext) 로부터 직접 사용해야 할 경우에 ApplicationContextAware 인터페이스를 구현받아, 따로 선언하지 않고도 다른 객체를 직접 사용할 수 있다.


◎LifeBean(interface)

package test.exam07;

public interface LifeBean {
	void lifeMessage();
}

◎LifeBeanImpl

package test.exam07;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import test.exam07.LifeBean;

public class LifeBeanImpl implements LifeBean, BeanNameAware, ApplicationContextAware {

	
	private String beanName;
	private ApplicationContext context;
	
	//객체가 생성될 때 스프링의 ApplicationContext를 전달받는 메서드
	//ApplicationContext를 빈에 전달할 때 사용
	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		System.out.println("setApplicationContext");
		this.context = context;
	}

	@Override
	public void setBeanName(String beanName) {
		System.out.println("setBeanName");
		this.beanName = beanName;
	}

	@Override
	public void lifeMessage() {
			System.out.println("life 비지니스 로직 수행 중...");
			OtherBean other = (OtherBean)context.getBean("otherBean");
			other.otherMessage();
	}

}

위와 같이 lifeMessage 메서드에 다른 객체를 바로 사용이 가능하다.

 

◎OtherBean(interface)

package test.exam07;

public interface OtherBean {
	void otherMessage();
}

◎OtherBeanImpl1

package test.exam07;

public class OtherBeanImpl1 implements OtherBean {

	@Override
	public void otherMessage() {
		System.out.println("otherBean");
	}

}

◎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.exam07.LifeBeanImpl"></bean>
	<bean name = "otherBean" class="test.exam07.OtherBeanImpl1"></bean>
</beans>

◎Main

package test.exam07;

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

import test.exam07.LifeBean;

public class Main {

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

'[JAVA] > Spring' 카테고리의 다른 글

[Spring] STS: Servlet 자동 등록  (0) 2021.06.15
[Spring] STS 설치 & 초기 설정  (0) 2021.06.15
[Spring] bean 객체의 Life Cycle 관리  (0) 2021.06.14
[Spring] Bean 객체의 범위  (0) 2021.06.14
[Spring] Spring DI 객체 주입  (0) 2021.06.14
Comments