Spring源代码解释
在使用ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
InAbstractApplicationContext
类时ApplicationContextAware如何工作,该refresh()
方法具有以下代码:
prepareBeanFactory(beanFactory);
输入此方法,beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
将ApplicationContextAwareProcessor添加到AbstractrBeanFactory。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........
当springAbstractAutowireCapableBeanFactory
在方法中的中初始化bean时,initializeBean
调用applyBeanPostProcessorsBeforeInitialization
来实现bean的后期处理。该过程包括注入applicationContext。
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
当BeanPostProcessor实现Object来执行postProcessBeforeInitialization方法时,例如ApplicationContextAwareProcessor
之前添加的方法。
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.getBeanFactory()));
}
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);
}
}
}