- 前言
- 第一部分 核心实现
- 第 1 章 Spring 整体架构和环境搭建
- 第 2 章 容器的基本实现
- 第 3 章 默认标签的解析
- 第 4 章 自定义标签的解析
- 第 5 章 bean 的加载
- 第 6 章 容器的功能扩展
- 第 7 章 AOP
- 第二部分 企业应用
- 第 8 章 数据库连接 JDBC
- 第 9 章 整合 MyBatis
- 第 10 章 事务
- 第 11 章 SpringMVC
- 第 12 章 远程服务
- 第 13 章 Spring 消息
6.5.3 添加 ApplicationContextAwareProcessor 处理器
了解了属性编辑器的使用后,接下来我们继续通过 AbstractApplicationContext 的 prepareBeanFactory 方法的主线来进行函数跟踪。对于 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)) 其实主要目的就是注册个 BneaPostProcessor,而真正的逻辑还是在 ApplicationContextAwareProcessor 中。
ApplicationContextAwareProcessor 实现 BeanPostProcessor 接口,我们回顾下之前讲过的内容,在 bean 实例化的时候,也就是 Spring 激活 bean 的 init-method 的前后,会调用 BeanPost Processor 的 postProcessBeforeInitialization 方法和 postProcessAfterInitialization 方法。同样,对于 ApplicationContextAwareProcessor 我们也关心这两个方法。
对于 postProcessAfterInitialization 方法,在 ApplicationContextAwareProcessor 中并没有做过多逻辑处理。
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
那么,我们重点看一下 postProcessBeforeInitialization 方法。
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws
BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValue
ResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof
ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof
ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
invokeAwareInterfaces(bean);
return null;
}
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.
getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext. getBean
Factory()));
}
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);
}
}
}
postProcessBeforeInitialization 方法中调用了 invokeAwareInterfaces。从 invokeAwareInterfaces 方法中,我们或许已经或多或少了解了 Spring 的用意,实现这些 Aware 接口的 bean 在被初始化之后,可以取得一些对应的资源。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论