简介
在Spring学习中出现了很多以Aware结尾的类或者接口, 这些类主要是为了辅助自定义组件来访问Spring容器底层的组件, bean属性等.
列如我们想要在程序代码中获取ApplicationContext, BeanFactory, bean的名字等
Aware接口定义:
package org.springframework.beans.factory;
public interface Aware {
}
这是一个空接口定义, 以下是一些常用实现了该接口的Aware组件类:
常用的Aware:
- BeanNameAware: 能够获取bean的名称
- BeanFactoryAware:获取BeanFactory实例
- ApplicationContextAware:获取ApplicationContext
- MessageSourceAware:获取MessageSource(资源国际化)
- ResourceLoaderAware:获取ResourceLoader(资源加载器)
- EnvironmentAware:获取Environment(运行环境)
使用案例
- 实现对应的xxxAware
- 将自定义的类注入到容器中
@Component
public class AwareTest implements BeanNameAware, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setBeanName(String name) {
System.out.println("Bean的名称: " + name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("接收到了IOC容器的applicationContext: " + applicationContext);
this.applicationContext = applicationContext;
}
}
运行容器打印结果:
Bean的名称: awareTest
接收到了IOC容器的applicationContext: org.springframework.context.annotation.AnnotationConfigApplicationContext@2hf3bc2
总结:
把Spring底层的组件可以注入到自定义的bean中, 使用的是BeanPostProcessor原理, 在初始化之前调用set设置对应的值:
org.springframework.context.support.ApplicationContextAwareProcessor#invokeAwareInterfaces
private void invokeAwareInterfaces(Object bean) {
//如果bean实现了Aware接口, 调用对应的set进行装配
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware)bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
}
}
}
由此可见Aware组件功能是依赖BeanPostProcessor后置处理器来处理的.