Bahar kaynak kodu nasıl ApplicationContextAware çalışmalarını anlatmak üzere
kullandığınızda ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ise AbstractApplicationContext
sınıf, refresh()
metot aşağıdaki kodu vardır:
prepareBeanFactory(beanFactory);
bu yöntemi girin, beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
ApplicationContextAwareProcessor'ı AbstractrBeanFactory'ye ekleyecektir.
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));
...........
Spring AbstractAutowireCapableBeanFactory
, bean in yönteminde başlatıldığında , fasulye post sürecini uygulamaya initializeBean
çağırın applyBeanPostProcessorsBeforeInitialization
. süreç, applicationContext'i enjekte etmeyi içerir.
@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, postProcessBeforeInitialization yöntemini yürütmek için Object uyguladığında, örneğin ApplicationContextAwareProcessor
daha önce eklenenler.
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);
}
}
}