[英]Spring Framework does not call BeanPostProcessor unless a @autowired dependency exists
[英]Is @Autowired annotation handled by BeanPostProcessor in Spring?
我聲稱:
Spring
從Java Config中讀取Bean定義 BeanFactory
從防御中創建豆 BeanPostProcessors
注入 但是碰巧這是不准確的:
@Configuration
@ImportResource("classpath:spring_config.xml")
public class JavaConfig {
@Autowired
MyBean bean;
@Bean
public Boolean isBeanAutowired(){
return bean != null;
}
}
isBeanAutowired
bean已使用true
初始化。
問題 :
在上下文中的所有bean初始化之前,自動Autowired
邏輯如何工作?
是的@Autowired
由BeanPostProcessor
處理。 有關更多詳細信息,請參見org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
,如果您嘗試找到更多相關信息,請參閱org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
。
最后,Spring能夠分析一個Bean(需要連接的其他Bean)的依賴關系,並確定初始化Bean的順序。 因此,可以在創建bean之后直接自動接線。 有一個例外,當Spring嘗試解決循環依賴關系時會發生這種情況。 然后,Spring將創建兩個bean並將它們彼此自動連接。 雖然這僅受限制。
它不是一個簡單的BeanPostProcessor
。 如果您嘗試通過以下方式直接實現它:
public class MyAutowiredBeanPostProcessor implements BeanPostProcessor {
@Autowired
ApplicationContext context;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Class<?> beanClass = bean.getClass();
Field[] declaredFields = beanClass.getDeclaredFields();
for (Field field : declaredFields) {
MyAutowired annotation = field.getAnnotation(MyAutowired.class);
if (annotation != null){
Class<?> type = field.getType();
Object beanForInjection = context.getBean(type);
field.setAccessible(true);
ReflectionUtils.setField(field, bean, beanForInjection);
}
}
return bean;
}
您將看到它完美地“連接”了其他bean內的bean,但是卻沒有“連接” Java Configuration
類中的任何東西。 此外,如果僅通過postProcessBeforeInitialization
方法中的println beanName
跟蹤Bean進入bpp的順序,您將看到:
Bean came to bpp: org.springframework.context.event.internalEventListenerProcessor
Bean came to bpp: org.springframework.context.event.internalEventListenerFactory
Bean came to bpp: javaConfig
Initialized isBeanAutowired, and myBean is: null
Bean came to bpp: isBeanAutowired
Bean came to bpp: myBean
分析一個Bean(需要連接的其他Bean)的依賴關系,並確定初始化Bean的順序。
因此, AutowiredAnnotationBeanPostProcessor
聽起來像是對BPP初始原理的少許違反。 這不再是單一的責任。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.