I claimed that:
Spring read bean definitions from java configBeanFactory Create beans from defenitionsBeanPostProcessors
But it happened that it's not accurate:
@Configuration
@ImportResource("classpath:spring_config.xml")
public class JavaConfig {
@Autowired
MyBean bean;
@Bean
public Boolean isBeanAutowired(){
return bean != null;
}
}
The isBeanAutowired bean was initialized with true.
Question:
How does it happen that Autowired logic work before all beans in context were initialized?
Yes @Autowired is handled by a BeanPostProcessor. See org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor for more details and as an entrypoint if you try to find out more on this.
https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html
In the end Spring is able to analyze the dependencies of a bean (the other beans that need to be wired) and determine an order, in which the beans will be initialized. Thereby it is possible, to autowire directly after creation of a bean. There is one exception, which occurs when Spring tries to resolve circular dependencies. Then Spring will create both beans and autowire them to each other. This works only limited though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With