zoukankan      html  css  js  c++  java
  • 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方法呢?
  • 相关阅读:
    Go断后,Dart冲前,Google的野心
    gcc dynamic load library
    Go http server 高并发
    还是Go 为了伟大的未来
    windows go dll 框架
    Go cookie
    Go web ajax project
    hdoj 2844 Coins
    hdoj 1203 I NEED A OFFER!
    hdoj 2546 饭卡
  • 原文地址:https://www.cnblogs.com/keyi/p/8946388.html
Copyright © 2011-2022 走看看