標籤:清除 thold highlight comment lin tar util 產生 name
在Web應用中,Spring容器通常採用聲明式方式配置產生:開發人員只要在web.xml中配置一個Listener,該Listener將會負責初始化Spring容器,MVC架構可以直接調用Spring容器中的Bean,無需訪問Spring容器本身。在這種情況下,容器中的Bean處於容器管理下,無需主動訪問容器,只需接受容器的依賴注入即可。
但在某些特殊的情況下,Bean需要實現某個功能,但該功能必須藉助於Spring容器才能實現,此時就必須讓該Bean先擷取Spring容器,然後藉助於Spring容器實現該功能。為了讓Bean擷取它所在的Spring容器,可以讓該Bean實現ApplicationContextAware介面。
下面樣本為實現ApplicationContextAware的工具類,可以通過其它類引用它以操作spring容器及其中的Bean執行個體。
[java] view plain copy
- 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執行個體變數來訪問容器本身。
例如:
在CacheUtil中通過spring容器建立CacheManager執行個體
[java] view plain copy
- public class CacheUtils {
- private static CacheManager cacheManager = ((CacheManager) SpringContextHolder.getBean("cacheManager"));
- }
ApplicationContextAware介面的作用