Spring:当我们也有自定义 init() 或 @PostConstuct 时,为什么需要 InitializingBean 的 afterPropertiesSet

Spring: Why is afterPropertiesSet of InitializingBean needed when we have also custom init() or @PostConstuct

当我们还自定义了 init() 时,为什么需要 afterPropertiesSet of InitializingBean @Bean(initMethod = "init") 还是 @PostConstuct? 我可以对其中一个执行哪些操作而不能对另一个执行? 我什么时候应该使用一个而不是另一个。 都是所有属性自动装配后触发的回调。

一般来说,如果一个 bean 实现 InitializingBean,首先调用 @PostConstruct,然后调用 afterPropertiesSet,然后调用 init-method

@PostConstruct 是一个 JSR-250 注解,而 init-methodInitializingBean 是 Spring 的 bean 初始化工具。

InitializingBean 与初始化方法

在 Spring 工具、init-methoddestroy-method 之间进行选择是推荐的方法,因为不直接依赖于 Spring 框架,我们可以创建自己的方法。 init-method 是一种独立于 Spring 调用自定义方法的方式,如果您决定使用其他框架,则可以重用此方法。

PostConstruct 与 Spring 工具

Spring 文档提供了关于首选初始化方式的清晰解释:

To interact with the container's management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans.

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.