ApplicationContextAware学习--存疑问题

时间:2024-05-01 20:45:03

先看下ApplicationContextAware的源码:

  1. package org.springframework.context;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.Aware;
  4. public abstract interface ApplicationContextAware extends Aware
  5. {
  6. public abstract void setApplicationContext(ApplicationContext paramApplicationContext)
  7. throws BeansException;
  8. }
我们可以看到,ApplicationContextAware继承了Aware接口,我们在看下这个接口中怎么定义的:
  1. package org.springframework.beans.factory;
  2. public abstract interface Aware
  3. {
  4. }
网上查了一下,继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法,并可自动获得ApplicationContext对象,前提是在spring配置文件中指定了这个类。
看下这段代码:
  1. public class SpringContextUtils implements ApplicationContextAware
  2. {
  3. private static ApplicationContext appContext;
  4. public void setApplicationContext(ApplicationContext applicationContext)
  5. throws BeansException
  6. {
  7. SpringContextUtils.appContext = applicationContext;
  8. }
  9. public static ApplicationContext getApplicationContext()
  10. {
  11. checkApplicationContext();
  12. return appContext;
  13. }
  14. @SuppressWarnings("unchecked")
  15. public static <T> T getBean(String beanName)
  16. {
  17. checkApplicationContext();
  18. return (T)appContext.getBean(beanName);
  19. }
  20. private static void checkApplicationContext()
  21. {
  22. if (null == appContext)
  23. {
  24. throw new IllegalStateException("applicaitonContext未注入");
  25. }
  26. }
  27. }

spring配置文件中定义:

  1. <!-- 定义Spring工具类 -->
  2. <bean class="com.njxph.utils.SpringContextUtils" />

以上,就可以获取bean了。

但是我有以下几点疑问:
1、ApplicationContextAware继承了Aware接口,但是Aware接口是空的,什么都没定义,为什么ApplicationContextAware还要继承Aware接口呢?
2、为什么继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法呢?