Spring Aware容器感知技术

Spring Aware是什么

Spring提供Aware接口能让Bean感知Spring容器的存在,即让Bean可以使用Spring容器所提供的资源。

Spring Aware的分类

几种常用的Aware接口如下。

Aware接口说明
ApplicationContextAware 能获取Application Context调用容器的服务
ApplicationEventPublisherAware 应用事件发布器,可以用来发布事件
BeanClassLoaderAware 能获取加载当前Bean的类加载器
BeanFactoryAware 能获取Bean Factory调用容器的服务
BeanNameAware 能获取当前Bean的名称
EnvironmentAware 能获取当前容器的环境属性信息
MessageSourceAware 能获取国际化文本信息
ResourceLoaderAware 获取资源加载器读取资源文件
ServletConfigAware 能获取到ServletConfig
ServletContextAware 能获取到ServletContext

更多的可以看它的继承图。

Spring Aware的使用

如要获取容器中的某个Bean,可以继承ApplicationContextAware,让这个Bean拥有调用容器服务的能力。

  1. import org.springframework.beans.BeansException;

  2. import org.springframework.context.ApplicationContext;

  3. import org.springframework.context.ApplicationContextAware;

  4.  

  5. public class SpringAppContext implements ApplicationContextAware {

  6.  

  7.    private static ApplicationContext applicationContext = null;

  8.  

  9.    @Override

  10.    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

  11.        if (SpringAppContext.applicationContext == null) {

  12.            SpringAppContext.applicationContext = applicationContext;

  13.        }

  14.    }

  15.  

  16.    public static ApplicationContext getApplicationContext() {

  17.        return applicationContext;

  18.    }

  19.  

  20.    public static Object getBean(String name) {

  21.        return getApplicationContext().getBean(name);

  22.  

  23.    }

  24.  

  25.    public static <T> T getBean(Class<T> clazz) {

  26.        return getApplicationContext().getBean(clazz);

  27.    }

  28.  

  29.    public static <T> T getBean(String name, Class<T> clazz) {

  30.        return getApplicationContext().getBean(name, clazz);

  31.    }

  32.  

  33. }

posted @ 2018-06-01 16:09  章鱼哥哥  阅读(210)  评论(0编辑  收藏  举报