Spring código fuente para explicar cómo funciona ApplicationContextAware
cuando usa ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
En AbstractApplicationContext
clase, el refresh()
método tiene el siguiente código:
prepareBeanFactory(beanFactory);
ingrese este método, beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
agregará ApplicationContextAwareProcessor a 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));
...........
Cuando spring initialize bean in AbstractAutowireCapableBeanFactory
, en el método initializeBean
, llame applyBeanPostProcessorsBeforeInitialization
para implementar el proceso de post de bean. el proceso incluye inyectar el 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;
}
cuando BeanPostProcessor implemente Object para ejecutar el método postProcessBeforeInitialization, por ejemplo, ApplicationContextAwareProcessor
el agregado antes.
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);
}
}
}