Programming/Java
Spring - 어디에서나 Spring 컨터이너 Bean 객체 얻어오기
파란크리스마스
2016. 2. 27. 01:05
728x90
출처 : 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");
728x90