一、Aware接口源码
如下代码,Aware是一个空的接口,该接口并未定义方法。看注释说:Aware是一个标记作用的接口,具体方法由子类去定义和实现,实现该接口的bean会被Spring以回调的方式进行通知、告诉某个阶段某件事情发生了。
/**
* 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.
*
* <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}.
* Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor}
* for an example of processing specific {@code *Aware} interface callbacks.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
*/
public interface Aware {
}
二、Aware接口的作用
- 通过Aware接口可以获取Spring容器相关信息
- @Autowired等注解的解析需要用到bean后处理器,属于是扩展功能,但是Aware接口属于是内置功能,不加任何扩展,Spring就能识别出。
- Spring 提供Aware接口机制,给外部的类提供获取spring内部信息的能力。
通俗一点讲:就比如:若Spring检测到bean实现了Aware接口,则会为其注入相对应的依赖,所以通过让bean实现Aware接口,则能在bean中获得对应的容器资源
三、常用Aware接口和作用
类名 | 作用 |
---|---|
BeanNameAware | 获得容器中bean的名称 |
BeanClassLoaderAware | 获得类加载器 |
BeanFactoryAware | 获得bean工厂 |
EnvironmentAware | 获得环境变量 |
EmbeddedValueResoverAware | 获得Spring容器加载的properties文件属性值 |
ApplicationEventPublisherAware | 获得应用时间发布器 |
MessageSourceAware | 获得文本信息 |
ApplicationContextAware | 获得当前应用上下文 |
四、案例
虚拟场景:Spring中管理的对象分为两类,一类是用户自定义的对象,一类是Spring容器对象,比如Application BeanFactory等。用户自定义的对象,在注入时可以直接使用@Autowared等方法,但是如果需要使用容器对象,该怎么注入呢?
这个时候 我们考虑Spring的一个扩展方法:ApplicationContextAware接口,实现容器对象的注入
接口源码:
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext var1) throws BeansException;
}
如何使用:
创建即ApplicationContextAware接口的实现类,实现类中定义局部变量applicationContext,实现setApplicationContext方法,将容器对象接收到applicationContext中。
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
return (T)applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> className) {
return applicationContext.getBean(className);
}
}