跳转至

Bean 的生命週期

啟動Spring Boot後 ,創建空的Spring 容器出來

創建Bean

  1. @Component
  2. @Configuration + @Bean

初始化Bean

  1. @PostConstruct
  2. 實現InitializingBean

Bean 可以被使用了

started DemoApplication

啟動 Spring Boot 
-> 創建 Bean myController 
-> 初始化 myController 
-> Bean myController 可以被使用了

先決條件

  • 要所有Bean都可以被使用之後 ,Spring Boot 才會運行成功 (只要有一個失敗就不行)
  • Bean之間的依賴關係處理

ex:

@RestController
public class MyController{
    @Autowired 
    private Printer printer;

    @RequestMapping("/test")
    public String test(){
        printer.print("hello world!");
        return "Hello World";
    }
}
因為 @Autowired 註解他是會根據變數的類型去Spring 容器中尋找符合類型的bean

所以依序是

  1. 啟動Spring Boot
  2. 創建 Bean myController
  3. 發現這個 @Autowired ,去Spring 容器中 去找到一個Printer類型的bean 然後就注入到MyController 裡面 (myController 它依賴於Printer類型的這個bean)
  4. 創建 Bean hpPrinter → 初始化 Bean hpPrinter → Bean hpPrinter可以使用
  5. 將hpPrinter注入 myController
  6. myController 順利創建後 → 初始化 Bean myController → Bean myController 可以使用

循環依賴的錯誤例子

@Component
public class A{
    @Autowired 
    private B b; // A依賴於B
}

@Component
public class B{
    @Autowired 
    private A a; // B依賴於A
}

重點回顧

  1. Bean 生命週期: 創建 -> 初始化 -> 可以被別人拿來用
  2. 創建時若有依賴其他bean ,則Spring 會回過頭去 創建+初始化 那個被依賴的bean
  3. 不要寫出循環依賴的code