ApplicationContextAware學習--存疑問題


先看下ApplicationContextAware的源碼:

 
 
[java]  view plain  copy
 
  1. package org.springframework.context;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.beans.factory.Aware;  
  5.   
  6. public abstract interface ApplicationContextAware extends Aware  
  7. {  
  8.   public abstract void setApplicationContext(ApplicationContext paramApplicationContext)  
  9.     throws BeansException;  
  10. }  
我們可以看到,ApplicationContextAware繼承了Aware接口,我們在看下這個接口中怎么定義的:
 
[java]  view plain  copy
 
  1. package org.springframework.beans.factory;  
  2.   
  3. public abstract interface Aware  
  4. {  
  5. }  
 
網上查了一下,繼承了ApplicationContextAware接口的類,在加載spring配置文件時,會自動調用接口中的setApplicationContext方法,並可自動獲得ApplicationContext對象,前提是在spring配置文件中指定了這個類。
 
看下這段代碼:
 
[java]  view plain  copy
 
  1. public class SpringContextUtils implements ApplicationContextAware  
  2. {  
  3.     private static ApplicationContext appContext;  
  4.       
  5.     public void setApplicationContext(ApplicationContext applicationContext)  
  6.         throws BeansException  
  7.     {  
  8.         SpringContextUtils.appContext = applicationContext;  
  9.     }  
  10.       
  11.     public static ApplicationContext getApplicationContext()  
  12.     {  
  13.         checkApplicationContext();  
  14.         return appContext;  
  15.     }  
  16.       
  17.     @SuppressWarnings("unchecked")  
  18.     public static <T> T getBean(String beanName)  
  19.     {  
  20.         checkApplicationContext();  
  21.         return (T)appContext.getBean(beanName);  
  22.     }  
  23.       
  24.     private static void checkApplicationContext()  
  25.     {  
  26.         if (null == appContext)  
  27.         {  
  28.             throw new IllegalStateException("applicaitonContext未注入");  
  29.         }  
  30.     }  
  31. }  

spring配置文件中定義:
 
[plain]  view plain  copy
 
  1. <!-- 定義Spring工具類 -->  
  2.    <bean class="com.njxph.utils.SpringContextUtils" />  

以上,就可以獲取bean了。
 
但是我有以下幾點疑問:
 
1、ApplicationContextAware繼承了Aware接口,但是Aware接口是空的,什么都沒定義,為什么ApplicationContextAware還要繼承Aware接口呢?
 
2、為什么繼承了ApplicationContextAware接口的類,在加載spring配置文件時,會自動調用接口中的setApplicationContext方法呢?


免責聲明!

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



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