簡體   English   中英

為什么@PostConstruct導致NullPointerException?

[英]Why @PostConstruct causes 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類,我們將在輸出中得到它:

第二個純文本:空

第一篇課文:第二個字

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

這只是關於執行順序。 其中之一必須首先運行!

  1. Spring通過所有@Autowiring運行(工作正常)
  2. Spring以某種順序遍歷所有@PostConstruct

在你的, One的@PostConstruct恰好先運行,那么Two的算賬。

如果希望Bean OneTwo之前初始化,則可以添加@DependsOn

@DependsOn({"One"})
@Service
public class Two {

可以用於直接或間接用Component注釋的任何類,或用Bean注釋的方法。

盡管您在其他日志中將得到null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM