SF的依赖注入亮点之一就是所有的Bean实现都不需要去考虑运行时要如何注入的Spring容器(就是无感知),Bean和Spring容器耦合度很低(就是无侵入编程)。
实际开发的时候,有时Bean需要用到Spring容器本身的功能资源,就需要提供一种机制让Bean能意识到Spring容器到存在并能调用Spring所提供的资源,这个机制就是由Aware来实现的。
类作用
A 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.The actual method signature is determined by individual subinterfaces but should typically consist of just one void-returning method that accepts a single argument.
1、org.springframework.beans.factory.aware是一个超级接口标记(空接口,代码如下),代表bean可以通过回调方法得到特定的框架对象。
//aware空接口定义
public interface Aware {
}
2、aware是实际的方法签名由各个子接口确定,但通常只包含一个接受单个参数的void返回方法。
类应用
1、Spring提供如下继承了Aware的接口(代表对应的框架特定对象):ApplicationContextAware、BeanFactoryAware、EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationStartupAware
此类接口代码定义如下:
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext);
}
2、如我们的类需要用到相关能力,直接实现对应接口即可。在运行时,bean初始化后ApplicationContext会自动感知并把对应对象设置给bean。
3、通常实现aware能力的类命名为“bean名字+Aware”。
应用举例
package com.learnsf.service;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component("TestAware")
public class TestAware implements ApplicationContextAware{
ApplicationContext app;
//实现ApplicationContextAware接口
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
System.out.println("初始化感知ApplicationContext");
this.app = applicationContext;
System.out.println(app);
}
}
该类实现了ApplicationContextAware接口,在初始化时会把容器注入到类属性app,可以达到两个目录:
1、类就可以通过属性app调用容器方法了。
2、另一个用处是在初始化TestAware时,可以在方法setApplicationContext做一些特殊事情。
Aware接口
SF提供如下Aware接口:
1、初始化前框架调用
BeanNameAware :回传beanName
BeanClassLoaderAware:回传容器的Bean的类加载器
BeanFactoryAware:回传容器BeanFactory
2、ApplicationContextAwareProcessor(继承自BeanPostProcessor)会在初始化前这个步骤中进行其他Aware的回调:
EnvironmentAware:回传容器环境变量
EmbeddedValueResolverAware:回传容器中占位符解析器
ResourceLoaderAware:回传容器资源加载器
ApplicationEventPublisherAware:回传容器事件发布器
MessageSourceAware:回传容器国际化资源
ApplicationStartupAware:回传应用其他监听对象,可忽略
ApplicationContextAware:回传Spring容器ApplicationContext
其它
Aware根接口标记定义在org.springframework.beans.factory模块中,但实际大多数继承接口都在模块context或模块core中,aware根接口似乎定义在core中更恰当,估计设计理念的出发点是提供BeanFactoryAware,后面才衍生的其它Aware继承对象。