最近看项目中的代码,发现有个获取spring bean的地方,直接调用了那个获取bean的方法,但是不明白这个bean到底是怎么来的,查了一下:
先看下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方法呢?
以上,欢迎大家评论,希望各位飘过的大牛帮忙解答下,3Q