@PostConstruct 和 Autowired Constructor 之间有什么区别?

What are the differences between @PostConstruct and Autowired Constructor?

我想知道下面两个例子有什么区别。一种是使用 @PostConstruct init 方法来确保自动装配的 bean 被初始化,另一种是使用带有 @Autowired 的构造函数来确保任何需要的 bean 被初始化。

很好奇

  1. 如果有任何功能差异
  2. 如果一个比另一个好,为什么? (可能是初始化速度快,调用栈少,内存占用少等)

提前致谢:)

@Component
public class MyBean {

    @Autowired
    public MyBean(SomeOtherBean someOtherBean) {
        ...
    }
    ...
}
@Component
public class MyBean {

    @Autowired 
    private SomeOtherBean someOtherBean;

    @PostConstruct
    public void init() {
        ...
    }
    ...
}

Autowired 构造函数不会创建实例,除非它有可用的其他 bean,这意味着它很快就会失败,甚至不会在其他 bean 可用之前尝试创建实例。如果您没有自动装配的构造函数,它将创建实例并且该 bean 在容器中可用,然后在其他 bean 可用时注入它。 @PostConstruct 注释方法中的任何内容都将在创建实例后执行。请阅读以下内容会有更好的想法

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#spring-core

在第一种情况下,如果我要在 none Spring 框架项目中使用 MyBean.class 而不是,我需要传递 SomeOtherBean 所以我知道对象是正确创建。但在第二种情况下,我会完成 new MyBean(),然后在使用它时会得到 NullPointerException,因为该对象依赖于 SomeOtherBean。 所以第一个更干净。