Spring Aware automatic assembly has two implementations:
- Execute the invokeAwareMethods method in the initialize Bean method for initializing beans
- It is implemented through the post processor ApplicationContextAwareProcessor, which implements the BeanPostProcessor interface.
invokeAwareMethods
When we initialize beans, in order to ensure that part of Aware must be executed before the postProcessBeforeInitialization method of the postprocessor, invokeAwareMethods method is called directly before the beans are initialized. The source code is as follows:
private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader()); } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }
ApplicationContextAwareProcessor
In addition to the Aware involved in the appeal, the automatic assembly of the remaining parts of Aware is implemented in the Application Context Aware Processor # postProcess BeforeInitialization, which eventually calls the invoke Aware Interfaces method. The source code is as follows:
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(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); } } }
summary
From the above source code, we can see that no matter which way we implement it, our execution process is the same:
- Determine whether the Aware interface is implemented
- Judging which Aware interface is specifically implemented
- A Special Method of Direct Calling XxAware Interface to Realize Automatic Assembly of XxxAware