over 8 years ago
有時需求必須額外開Thread,但並不是用Spring管理的方式,但卻也想取得原來原本就做好的類別
透過ApplicationContextAware來達成此需求
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextHelper implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean( String beanName ) {
return applicationContext.getBean( beanName );
}
}
在特定檔聲明
<!-- 輔助類別,幫助在非spring管理下的物件取得spring管理的物件 -->
<bean id="SpringApplicationContext" class="com.secom.mobile.common.ApplicationContextHelper"></bean>
取得方式
MessageSource messageSource = (MessageSource)ApplicationContextHelper.getBean("messageSource");