Spring启动时相关加载顺序讨论 spring注解@postConstruct与constructor与@Autowired的启动顺序

spring注解@postConstruct与constructor与@Autowired的启动顺序

@Postcontruct’在依赖注入完成后自动调用,例如要将对象a注入到对象b中,首先需要生成对象a才能将a注入到b中,所以一个类中只有成员变量aAutowired注入是发生在A的构造方法完成之后的,如果在生成对象时完成某些被初始化操作,而这个有依赖与依赖注入。@postConstructconstructor@Autowired的启动顺序:

constructor(构造方法)——>@Autowired——>@postConstruct   

还有一个加载的方法就是实现InitializingBean接口其中重写afterPropertiesSet()方法,这个方法在@postConstruct方法之后运行,还有李刚一个方法就是init-mathod方法该方法在afterPropertiesSet()方法之后运行,总结之后的顺序为:

constructor(构造方法)——>@Autowired——>@postConstruct——>afterPropertiesSet()àinit-method


Spring InitializingBean init-method @PostConstruct 执行顺序

Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:
 
通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。 

1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用

2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖

3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。

 

最后,给出结论,Bean在实例化的过程中:

 
  
实现BeanDefinitionRegistryPostProcessor -> Constructor ——> @Autowired——>@PostConstruct ——> InitializingBean ——> init-method

猜你喜欢

转载自blog.csdn.net/weixin_42231507/article/details/80998817