代码:https://gitee.com/free/boot-order/tree/master/src/main/java/com/github/abel533/autowired
结合 PostProcessor 时的执行顺序
InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation - userExt
SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors - userExt
UserExt#constructor
InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation - userExt
InstantiationAwareBeanPostProcessor#postProcessProperties - userExt
UserExt@Value("${autowired.testValue}")
UserExt@Value("#{systemProperties['os.name']}")
UserExt@Autowired
BeanPostProcessor#postProcessBeforeInitialization - userExt
BeanPostProcessor#postProcessAfterInitialization - userExt
第 0 步可以通过返回 bean 来替代默认创建实例的方法。
第 1 步可以返回一个可用的构造方法。
第 2 步为构造方法注入,执行的比字段和方法注入要早(理所当然)
第 3 步时实例已经创建,但是还未注入属性。
第 4 步时,示例中什么也没做,实际上在 AutowiredAnnotationBeanPostProcessor#postProcessProperties
方法中,对 @Autowired
和 @Value
的字段或方法进行了注入。
第 5~7 步时,也就是 AutowiredAnnotationBeanPostProcessor
对方法和字段进行注入。
第 8 步时,在执行实例的初始化方法前进行调用。后续会调用 bean 的初始化方法。
第 9 步时,已经执行完成了初始化方法,此时的 bean 已经是最终的结果了,但是你仍然可以在此对 bean 进行处理,例如再包装一层代理。
结合 Bean 的生命周期时的顺序
UserExt#constructor
构造方法UserExt@Value("${autowired.testValue}")
注入UserExt@Value("#{systemProperties['os.name']}")
注入@PostConstruct
从这儿往下都是初始化和销毁方法InitializingBean#afterPropertiesSet
@PostConstruct
InitializingBean#afterPropertiesSet
@Bean(initMethod)
SmartLifecycle#isRunning
SmartLifecycle#start
SmartLifecycle#isRunning
SmartLifecycle#start
SmartLifecycle#isRunning
SmartLifecycle#stop
SmartLifecycle#isRunning
SmartLifecycle#stop
@PreDestroy
DisposableBean#destroy
@Bean(destroyMethod)
@PreDestroy
DisposableBean#destroy
也就是说,在生命周期中,所有注入的数据都已经可以使用。