Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is @Autowired annotation handled by BeanPostProcessor in Spring?

Tags:

java

spring

I claimed that:

  1. Spring read bean definitions from java config
  2. BeanFactory Create beans from defenitions
  3. Then dependencies are injected by BeanPostProcessors

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?

like image 372
Rudziankoŭ Avatar asked Oct 25 '16 11:10

Rudziankoŭ


1 Answers

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.

like image 113
Benny Avatar answered Oct 13 '22 20:10

Benny