先看下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方法呢?
