ApplicationContextAware 介面的作用

來源:互聯網
上載者:User

標籤:部分   return   warning   方式   color   exti   stat   oid   容器   

介面說明:當一個類實現了這個介面之後,這個類就可以方便地獲得 ApplicationContext 中的所有bean。換句話說,就是這個類可以直接擷取Spring設定檔中,所有有引用到的bean對象。

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

但在某些特殊的情況下,Bean需要實現某個功能,但該功能必須藉助於Spring容器才能實現,此時就必須讓該Bean先擷取Spring容器,然後藉助於Spring容器實現該功能。為了讓Bean擷取它所在的Spring容器,可以讓該Bean實現ApplicationContextAware介面。

下面樣本為實現ApplicationContextAware的工具類,可以通過其它類引用它以操作spring容器及其中的Bean執行個體。

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.");      }    }  

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

ApplicationContextAware 介面的作用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.