0
点赞
收藏
分享

微信扫一扫

Spring 执行顺序:@Autowired 和 @Value 注解


​​回目录​​

代码:​​https://gitee.com/free/boot-order/tree/master/src/main/java/com/github/abel533/autowired​​

结合 PostProcessor 时的执行顺序

  1. ​InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation - userExt​
  2. ​SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors - userExt​
  3. ​UserExt#constructor​
  4. ​InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation - userExt​
  5. ​InstantiationAwareBeanPostProcessor#postProcessProperties - userExt​
  6. ​UserExt@Value("${autowired.testValue}")​
  7. ​UserExt@Value("#{systemProperties['os.name']}")​
  8. ​UserExt@Autowired​
  9. ​BeanPostProcessor#postProcessBeforeInitialization - userExt​
  10. ​BeanPostProcessor#postProcessAfterInitialization - userExt​

第 0 步可以通过返回 bean 来替代默认创建实例的方法。

第 1 步可以返回一个可用的构造方法。

第 2 步为构造方法注入,执行的比字段和方法注入要早(理所当然)

第 3 步时实例已经创建,但是还未注入属性。

第 4 步时,示例中什么也没做,实际上在 ​​AutowiredAnnotationBeanPostProcessor#postProcessProperties​​​ 方法中,对 ​​@Autowired​​​ 和 ​​@Value​​ 的字段或方法进行了注入。

第 5~7 步时,也就是 ​​AutowiredAnnotationBeanPostProcessor​​ 对方法和字段进行注入。

第 8 步时,在执行实例的初始化方法前进行调用。后续会调用 bean 的初始化方法。

第 9 步时,已经执行完成了初始化方法,此时的 bean 已经是最终的结果了,但是你仍然可以在此对 bean 进行处理,例如再包装一层代理。

结合 Bean 的生命周期时的顺序

1. ​​UserExt#constructor​​ 构造方法
2. ​​UserExt@Value("${autowired.testValue}")​​ 注入
3. ​​UserExt@Value("#{systemProperties['os.name']}")​​ 注入
4. ​​@PostConstruct​​ 从这儿往下都是初始化和销毁方法
5. ​​InitializingBean#afterPropertiesSet​​
6. ​​@PostConstruct​​
7. ​​InitializingBean#afterPropertiesSet​​
8. ​​@Bean(initMethod)​​
9. ​​SmartLifecycle#isRunning​​
10. ​​SmartLifecycle#start​​
11. ​​SmartLifecycle#isRunning​​
12. ​​SmartLifecycle#start​​
13. ​​SmartLifecycle#isRunning​​
14. ​​SmartLifecycle#stop​​
15. ​​SmartLifecycle#isRunning​​
16. ​​SmartLifecycle#stop​​
17. ​​@PreDestroy​​
18. ​​DisposableBean#destroy​​
19. ​​@Bean(destroyMethod)​​
20. ​​@PreDestroy​​
21. ​​DisposableBean#destroy​​

也就是说,在生命周期中,所有注入的数据都已经可以使用。


举报

相关推荐

0 条评论