ApplicationContextAware獲取bean


ApplicationContextAware獲取bean

概述

  • 在某些特殊的情況下,Bean需要實現某個功能,但該功能必須借助於Spring容器才能實現,此時就必須讓該Bean先獲取Spring容器,然后借助於Spring容器實現該功能。為了讓Bean獲取它所在的Spring容器,可以讓該Bean實現ApplicationContextAware接口。
  • Spring容器會檢測容器中的所有Bean,如果發現某個Bean實現了ApplicationContextAware接口,Spring容器會在創建該Bean之后,自動調用該Bean的setApplicationContextAware()方法,調用該方法時,會將容器本身作為參數傳給該方法——該方法中的實現部分將Spring傳入的參數(容器本身)賦給該類對象的applicationContext實例變量,因此接下來可以通過該applicationContext實例變量來訪問容器本身。

使用

public class SpringContextHolder implements ApplicationContextAware {  
    private static ApplicationContext applicationContext = null;  
  
    /** 
     * 獲取靜態變量中的ApplicationContext. 
     */  
    public static ApplicationContext getApplicationContext() {  
        assertContextInjected();  
        return applicationContext;  
    }  
  
    /** 
     * 從靜態變量applicationContext中得到Bean, 自動轉型為所賦值對象的類型. 
     */  
    @SuppressWarnings("unchecked")  
    public static <T> T getBean(String name) {  
        assertContextInjected();  
        return (T) applicationContext.getBean(name);  
    }  
  
    /** 
     * 從靜態變量applicationContext中得到Bean, 自動轉型為所賦值對象的類型. 
     */  
    public static <T> T getBean(Class<T> requiredType) {  
        assertContextInjected();  
        return applicationContext.getBean(requiredType);  
    }  
  
    /** 
     * 清除SpringContextHolder中的ApplicationContext為Null. 
     */  
    public static void clearHolder() {  
        applicationContext = null;  
    }  
  
    /** 
     * 實現ApplicationContextAware接口, 注入Context到靜態變量中. 
     */  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextHolder.applicationContext = applicationContext;  
    }  
  
    /** 
     * 檢查ApplicationContext不為空. 
     */  
    private static void assertContextInjected() {  
        Validate.validState(applicationContext != null,  
                "applicaitonContext屬性未注入, 請在applicationContext.xml中定義SpringContextHolder.");  
    }  
  
} 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM