[英]Spring autowiring order and @PostConstruct
我對Spring中的自動布線順序和@PostConstruct
邏輯有疑問。 例如,下面的演示代碼我有一個主要的Spring Boot類:
@SpringBootApplication
public class Demo1Application {
@Autowired
BeanB beanb;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
和2 @Service
定義:
@Service
public class BeanB {
@Autowired
private BeanA beana ;
@PostConstruct
public void init(){
System.out.println("beanb is called");
}
public void printMe(){
System.out.println("print me is called in Bean B");
}
}
@Service
public class BeanA {
@Autowired
private BeanB b;
@PostConstruct
public void init(){
System.out.println("bean a is called");
b.printMe();
}
}
我有以下輸出:
豆a被稱為
打印我在Bean B中調用
beanb被稱為
我的問題是如何像上面的場景一樣一步一步地進行自動裝配?
而如何printMe()
的方法beanb
被稱為不調用其@PostConstruct
第一?
下面應該是可能的順序
beanb
開始自動裝配 Beanb
類初始化期間,beana開始自動裝配 @PostConstruct
即beana的init()
被調用 init()
, System.out.println("bean a is called");
被叫 b.printMe();
被調用導致System.out.println("print me is called in Bean B");
執行 beana
完成了@PostConstruct
即init()
的beanb
被調用 System.out.println("beanb is called");
被叫 理想情況下,eclipse中的調試器可以更好地觀察到相同的情況。
Spring參考手冊解釋了如何解決循環依賴關系。 首先實例化bean,然后相互注入。
您的答案是正確的,如您在問題中所示。
現在獲得符號@Autowired
的概念。 在完成類加載后,所有@Autowired
對象都被初始化並加載到內存中。
現在這是你的SpringBootApplication
@SpringBootApplication
public class Demo1Application {
@Autowired
BeanB beanb; // You are trying to autowire a Bean class Named BeanB.
在上面的控制台應用程序中,您嘗試自動裝配並注入BeanB
類型的對象。
現在,這是您對BeanB
的定義
@Service
public class BeanB {
@Autowired
private BeanA beana ;
在BeanB
類中,您嘗試注入類BeanA
的Object,它也在您的控制台Project中定義。
因此,在您的Demo1Application
中注入類BeanB
的Object必須注入類BeanA
的Object。 現在首先創建BeanA
類對象。
現在,如果你看到你的Class BeanA
的定義
@Service
public class BeanA {
@Autowired
private BeanB b;
@PostConstruct // after Creating bean init() will be execute.
public void init(){
System.out.println("bean a is called");
b.printMe();
}
}
因此,在注入Object BeanA
方法之后,綁定@PostContruct
注釋將會執行。
所以,執行流程將是......
System.out.println("bean a is called");
System.out.println("print me is called in Bean B");
System.out.println("beanb is called");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.