ApplicationContextAware
1 ApplicationContextAware
当一个类实现了这个接口(ApplicationContextAware)之后,Aware接口的Bean在被初始之后,可以取得一些相对应的资源,这个类可以直接获取spring 配置文件中 所有引用(注入)到的bean对象。
设置该对象在其中运行的ApplicationContext
通常这个调用将被用来初始化对象
在普通bean属性的装配之后但在初始回调例如InitializingBean#afterPropertiesSet()或一个自定义的初始方法之前调用
在链接ResourceLoaderAware#setResourceLoader之后调用
在使用spring整合的项目时,有时候需要获取ApplicationContext中的bean,就需要在spring加载过程中将ApplicationContext注入到工具类当中,在使用时,直接从工具类中获取对应的bean,这样就很方便。
有如下的几种方式:
直接使用spring的xml配置加载
在Web应用中,使用Servlet或者Linsener,通过WebApplicationContext将ApplicationContext注入
实现ApplicationContextAware接口;该方法比较方便,推荐使用该方法;
要运行的ApplicationContext希望被通知的任何对象实现的接口。
实现这个接口是有道理的,例如当一个对象需要访问一个集合的合作bean。
注意,通过bean引用的配置比实现此接口更适合用于bean的查找目的。
如果对象需要访问file资源,即要调用getResource,想要发布应用程序事件,或者需要访问MessageSource,那么也可以实现此接口。但是,在这种特定情况下,最好是实现更具体的ResourceLoaderAware,ApplicationEventPublisherAware或MessageSourceAware接口
请注意,文件资源依赖关系也可以以类型为org.springframework.core.io.Resource的bean属性公开,通过Struts填充,由bean工厂进行自动类型转换。这样就不需要实现任何回调接口,只是为了访问一个特定的文件资源。
在程序当中就可以直接从ApplictionContext中获取对应的bean了。
2 demo
@Component
public class SpringHelper implements ApplicationContextAware, EmbeddedValueResolverAware {
//静态ApplicationContext
private static ApplicationContext applicationContext;
private static StringValueResolver valueResolver;
public SpringHelper(){}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
/** 将框架初始化加载的ioc容器赋值给 静态ApplicationContext*/
SpringHelper.applicationContext = applicationContext;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
}
//获取Ioc容器
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
//通过class获取Bean
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过名称获取Bean
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过名称、class获取Bean
public static <T> T getBean(Class<T> clazz, String name){
return getApplicationContext().getBean(name, clazz);
}
}
@Component
public class AppUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
AppUtils.applicationContext = applicationContext;
}
public Object getObject(String id){
Object obj = null;
obj = applicationContext.getBean(id);
return obj;
}
public static String[] getNames(){
return applicationContext.getBeanDefinitionNames();
}
public static ApplicationContext getContext(){ return applicationContext; }
}