通過(guò)實(shí)現(xiàn) Aware 接口,可以在 Spring 啟動(dòng)時(shí)懦尝,調(diào)用接口定義的方法伏伯,將 Spring 底層的一些組件注入到自定義的 Bean 中。
下面列出了幾個(gè) Spring 在 Aware 接口基礎(chǔ)上婶肩,進(jìn)行擴(kuò)展的接口办陷,分別會(huì)在創(chuàng)建 Bean 時(shí)直接執(zhí)行,或者通過(guò) BeanPostProcessor 間接執(zhí)行:
// 應(yīng)用上下文 ApplicationContext
ApplicationContextAware
// 事件派發(fā)器
ApplicationEventPublisherAware
// 國(guó)際化
MessageSourceAware
// 資源加載器
ResourceLoaderAware
// 環(huán)境
EnvironmentAware
// 值解析器
EmbeddedValueResolverAware
BeanFactoryAware
// Bean 名字
BeanNameAware
// 類(lèi)加載器
BeanClassLoaderAware
// @Import 相關(guān)
ImportAware
直接執(zhí)行
見(jiàn)Spring 后置處理器源碼中律歼,initializeBean() 調(diào)用的方法 invokeAwareMethods()民镜,這個(gè)方法分別會(huì)直接執(zhí)行 BeanNameAware、BeanClassLoaderAware险毁、BeanFactoryAware制圈,invokeAwareMethods()的源碼如下:
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) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
間接執(zhí)行
繼續(xù)看 invokeAwareMethods() 調(diào)用的 applyBeanPostProcessorsBeforeInitialization(),它會(huì)遍歷和執(zhí)行容器中所有的 BeanPostProcessor畔况,而 ApplicationContextAwareProcessor 也是 BeanPostProcessor 的一個(gè)實(shí)現(xiàn)類(lèi)鲸鹦,它的主要源碼如下:
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
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);
}
}
return bean;
}
ImportAware 見(jiàn)Spring AOP源碼
總結(jié)
調(diào)用 refresh()-->finishBeanFactoryInitialization(beanFactory); 創(chuàng)建 Bean 時(shí),會(huì)執(zhí)行 Aware 的一些實(shí)現(xiàn)類(lèi)跷跪。
- 通過(guò)直接執(zhí)行的方式馋嗜,執(zhí)行 Aware 的一些基礎(chǔ)接口方法。
- 通過(guò) BeanPostProcessor 間接執(zhí)行更高級(jí)的 Aware 實(shí)現(xiàn)類(lèi)吵瞻。