使用Spring的ApplicationContextAware接口

在我們的Web應用中,Spring容器通常採用聲明式方式配置產生。開發者只要在web.xml中配置一個Listener,該Listener將會負責初始化Spring容器,MVC框架可以直接調用Spring容器中的Bean,無需訪問Spring容器本身。在這種情況下,容器中的Bean處於容器管理下,無需主動訪問容器,只需接受容器的依賴注入即可。


但在某些特殊的情況下,Bean需要實現某個功能,但該功能必須藉助於Spring容器才能實現,此時就必須讓該Bean先獲取Spring容器,然後藉助於Spring容器實現該功能。爲了讓Bean獲取它所在的Spring容器,可以讓該Bean實現ApplicationContextAware接口。也就是說當一個類實現了這個接口之後,這個類就可以方便獲得ApplicationContext中的所有bean。換句話說,就是這個類可以直接獲取spring配置文件中,所有有引用到的bean對象。

工具類:

@Component
public class SpringContextHolder implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;
	/*
	 * (non-Javadoc)
	 * @see
	 * org.springframework.context.ApplicationContextAware#setApplicationContext
	 * (org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}
	
	public static <T> T getBean(Class<T> clazz) {
		return applicationContext.getBean(clazz);
	}
	
	public static void clearHolder() {
		applicationContext = null;
	}

}

Spring容器會檢測容器中的所有Bean,如果發現某個Bean實現了ApplicationContextAware接口,Spring容器會在創建該Bean之後,自動調用該Bean的setApplicationContext()方法,調用該方法時,會將容器本身作爲參數傳給該方法——該方法中的實現部分將Spring傳入的參數(容器本身)賦給該類對象的applicationContext實例變量,因此接下來可以通過該applicationContext實例變量來訪問容器本身。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章