1. Aware接口

在Spring Bean的整个生命周期中调用的所有接口方法中,有很多以Aware结尾的接口方法,各个XXXAware接口作用是什么?对开发者来说有没有用?

1.1. Aware单词释义

aware 英 [ə'weə]

adj. 意识到的;知道的;有…方面知识的;懂世故的

只看此英文单词,实在是想不出来spring中以Aware为后缀的接口的作用究竟是什么,下面我们看一下接口定义和描述;

1.2. Aware接口定义

/**
 * Marker superinterface indicating that a bean is eligible to be
 * notified by the Spring container of a particular framework object
 * through a callback-style method. Actual method signature is
 * determined by individual subinterfaces, but should typically
 * consist of just one void-returning method that accepts a single
 * argument.
 *
 * <p>Note that merely implementing {@link Aware} provides no default
 * functionality. Rather, processing must be done explicitly, for example
 * in a {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessor}.
 * Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor}
 * and {@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory}
 * for examples of processing {@code *Aware} interface callbacks.
 *
 * @author Chris Beams
 * @since 3.1
 */
public interface Aware {

}

从源码可以看出来:

  1. Aware是一个用来标记的顶层设计接口,不包括任务功能方法;实际的方法签名由它的子类来声明,一般来说,是只带一个参数且返回void的方法;
  2. Aware标记一个bean有资格让spring特定容器对象通过回调方法进行通知;

在使用spring时,我们把所有的bean交给spring容器进行管理,一般来讲,所有的bean专注于业务逻辑,它们不关心spring容器,也不知道自己在spring中是如何被管理的,在spring工厂中的代号是什么,换句话说,bean对于spring是无感知的。

spring提供了一系列的Aware接口作为hook,在不同的阶段调用不同的接口方法来通知一个bean,使bean可以对spring有所感知。

1.3. BeanNameAware

bean获取在BeanFactory中配置的名称(xml中的id或name),即一个实现了BeanNameAware接口的bean,可以获取其在工厂中的名称。

1.4. BeanFactoryAware

让bean对配置其BeanFactory有感知,即一个实现了BeanFactoryAware接口的bean,可以获取到配置它的BeanFactory实例。

其它的Aware类似,都是使一个bean对spring的某一方面有所感知,在特殊情况下,可以有用,但缺点也比较明显,就是对spring api耦合比较高,一般情况下,不建议使用。

Copyright © wychuan.com 2017 all right reserved,powered by Gitbook该文件修订时间: 2018-01-09 08:05:07

results matching ""

    No results matching ""