在普通的java類中獲得spring上下文

 package org.company.xxx;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
 * 獲取spring容器,以訪問容器中定義的其他bean
 */
public class SpringContextUtil implements ApplicationContextAware {
 
	// Spring應用上下文環境
	private static ApplicationContext applicationContext;
 
	/**
	 * 實現ApplicationContextAware接口的回調方法,設置上下文環境
	 */
	public void setApplicationContext(ApplicationContext applicationContext)throws BeansException  {
		SpringContextUtil.applicationContext = applicationContext;
	}
 
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
 
	/**
	 * 獲取對象
	 * 這裏重寫了bean方法,起主要作用
	 * @param name
	 * @return Object 一個以所給名字註冊的bean的實例
	 * @throws BeansException
	 */
	public static Object getBean(String beanId) throws BeansException {
		return applicationContext.getBean(beanId);
	}
}
 Bean配置:
<bean id="SpringContextUtil" class="org.company.xxx.SpringContextUtil" />
 實現了ApplicationContextAware接口,在Bean的實例化時會自動調用setApplicationContext()方法!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章