출처 : Get to Spring ApplicationContext from everywhere (The clean way)

Spring 컨터이너안의 Bean 객체를 어디에서든 얻어오는 Tip

ApplicationContextProvider 클래스

ApplicationContextProvider 클래스를 만들고, 이 클래스는 ApplicationContextAware 인터페이스를 구현합니다.

package com.iot.util;

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

public class ApplicationContextProvider implements ApplicationContextAware {
	
	private static ApplicationContext ctx = null;

	public static ApplicationContext getApplicationContext() {
		return ctx;
	}

	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		this.ctx = ctx;
	}

}

ApplicationContext 환경파일 추가

이 Bean을 ApplicationContext 구성 파일에 설정합니다.

	<bean id="applicationContextProvider" class="com.iot.util.ApplicationContextProvider"></bean>

BeanUtils 클래스

사용하기 쉽게 유틸클래스를 만듭니다.

package com.iot.util;

import org.springframework.context.ApplicationContext;

public class BeanUtils {
	
	public static Object getBean(String beanId) {
		
		ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();

		if( applicationContext == null ) {
			throw new NullPointerException("Spring의 ApplicationContext초기화 안됨");
		}
		
		/*
		String[] names = applicationContext.getBeanDefinitionNames();
		for (int i=0; i<names.length; i++) {
			System.out.println(names[i]);
		}
		*/
		
		return applicationContext.getBean(beanId);
	}
}

	DepartmentsService service = (DepartmentsService) BeanUtils.getBean("departmentsService");


저작자 표시
신고


 

티스토리 툴바