先看下ApplicationContextAware的源码:
- package org.springframework.context;
- import org.springframework.beans.BeansException;
- import org.springframework.beans.factory.Aware;
- public abstract interface ApplicationContextAware extends Aware
- {
- public abstract void setApplicationContext(ApplicationContext paramApplicationContext)
- throws BeansException;
- }
我们可以看到,ApplicationContextAware继承了Aware接口,我们在看下这个接口中怎么定义的:
- package org.springframework.beans.factory;
- public abstract interface Aware
- {
- }
网上查了一下,继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法,并可自动获得ApplicationContext对象,前提是在spring配置文件中指定了这个类。
看下这段代码:
- public class SpringContextUtils implements ApplicationContextAware
- {
- private static ApplicationContext appContext;
- public void setApplicationContext(ApplicationContext applicationContext)
- throws BeansException
- {
- SpringContextUtils.appContext = applicationContext;
- }
- public static ApplicationContext getApplicationContext()
- {
- checkApplicationContext();
- return appContext;
- }
- @SuppressWarnings("unchecked")
- public static <T> T getBean(String beanName)
- {
- checkApplicationContext();
- return (T)appContext.getBean(beanName);
- }
- private static void checkApplicationContext()
- {
- if (null == appContext)
- {
- throw new IllegalStateException("applicaitonContext未注入");
- }
- }
- }
spring配置文件中定义:
- <!-- 定义Spring工具类 -->
- <bean class="com.njxph.utils.SpringContextUtils" />
以上,就可以获取bean了。
但是我有以下几点疑问:
1、ApplicationContextAware继承了Aware接口,但是Aware接口是空的,什么都没定义,为什么ApplicationContextAware还要继承Aware接口呢?
2、为什么继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法呢?