ApplicationContextAware 接口的作用
这个接口有什么用?
当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
如何使用 ApplicationContextAware 接口
如何使用该接口?很简单。
1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法
public class SystemContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@SuppressWarnings("rawtypes")
public static Object getBean(Object beanName) {
if (beanName instanceof Class) {
return applicationContext.getBean(((Class) beanName).getName());
} else {
return applicationContext.getBean(beanName.toString());
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SystemContext.applicationContext = applicationContext;
}
}
如此一来,我们就可以通过该工具类,来获得 ApplicationContext,进而使用其getBean方法来获取我们需要的bean。
2、在Spring配置文件中注册该工具类
一、因为spring要建立属于自己的容器,就必须要加载自己的配置文件。
这个时候,需要注册ContextLoaderListener或者这个类的子类。
在web.xml加上以下的信息:
1
2
3
|
<
listener
>
<
listener-class
>org.springframework.web.context.ContextLoaderListener</
listener-class
>
</
listener
>
|
二、之所以我们能如此方便地使用该工具类来获取,正是因为Spring能够为我们自动地执行 setApplicationContext 方法,显然,这也是因为IOC的缘故,所以必然这个工具类也是需要在Spring的配置文件中进行配置的。
<!-- 初始化SystemContext,注入applicationContext --> <bean id="SystemContext" class="com.framework.system.engine.SystemContext" lazy-init="false"></bean>
3、编写方法进行使用
一切就绪,我们就可以在需要使用的地方调用该方法来获取bean了。
private static ShineApprovalService getShineApprovalService() {
return (ShineApprovalService) SystemContext.getBean(ShineApprovalServiceImpl.BEAN_NAME);
}