首页 > 解决方案 > 为什么@PostConstruct 会导致 NullPointerException?

问题描述

我正在学习 Spring Framework,在观看 Evgeniy Borisov 的讲座时,我遇到了以下代码:

假设我们有两个具有循环依赖的 bean:

第二个豆:

@Service
public class Two {

    @Autowired
    private One one;


    public String getWord() {
        return word;
    }

    private String word;


    @PostConstruct
    public void doSmth(){
        init();
        System.out.println("SECOND BEAN TEXT :"+one.getWord());
    }

        public void init(){
            word = "Second word";
    }
}

第一个豆子:

@Service
public class One {
    @Autowired
    private Two two;

    public String getWord() {
        return word;
    }
    private String word;

    @PostConstruct
    public void doSmth(){
        init();
        System.out.println("FIRST BEAN TEXT :"+two.getWord());
    }

    public void init(){
        word = "First bean";
    }
} 

并开始上课:

public class StartTests {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext("test");
    }
}

如果我们执行 StartTests 类,我们将在输出中得到:

第二个 Bean 文本:null

FIRST BEAN TEXT :第二个字

是的,我知道 @PostConstructor 在涉及所有代理之前执行,但我不明白为什么 First Bean 可以正常工作,而 Second Bean 不能

标签: javaspring

解决方案


这只是关于执行顺序。 毕竟其中一个必须先运行!

  1. 春天贯穿所有@Autowiring(工作正常)
  2. Spring以某种顺序贯穿所有的@PostConstructs

在您的情况下,One's @PostConstruct 恰好首先运行,然后是 THEN Two


推荐阅读