Spring boot IoC 筆記

Spring boot IoC 筆記

  • IoC 控制反轉

    • 把Object交給Spring Container管理,把控制權交給外部的Spring容器,降低耦合度
    • 方便管理Object的生命週期
    • 方便測試
  • @Componet

    • 只能用在class上
    • 將使用 @Componet 的 class 變成 交由Spring容器所管理的Object
  • Bean

    • 這些由Spring所創建,並且存放在Spring容器裡的Object,我們會稱呼這些Object為 bean
    • bean的名字,就是由class的第一個字母轉小寫而來的 (class HpPrinter => bean hpPrinter)
  • 如何使用bean

    • 在要使用bean的class中,也加入 @Componet ,並且在要使用 DI的變數上方加上 @Autowired
  • IntelliJ 萬用鍵

    • 遇到紅色波浪報錯時,可以使用alt + enter
  • @Autowired

    • 通常加在class裡面的變數上面
    • 根據 變數的類型 ,Spring boot會幫我們在 Spring 容器裡面,找到相符合的 bean,然後將其注入到 @Autowired 的變數
    • 使用 @Autowired 的變數類型,最好是使用 Interface 比較好
  • @Qualifier

    • 通常是加在class變數上,會跟 @Autowired一起用
    • 是用來指定 要載入bean的名字 (範例是,有兩個class都實作了 Printer 這個 Interface ,然後要注入的變數型別是 Printer ,所以要決定注入哪一個class的bean)
1
2
3
4
5
6
7
8
9
10
@Componet
Public class Teacher{
@Autowired
@Qulifier("hpPrinter")
Private Printer printer;

public void teach(){
printer.print("I'm a teacher");
}
}
  • 創建Bean的方法

    • 在class上加上 @Component 註解
    • 使用 @Configuration + @Bean 註解
  • @Configuration

    • 只能加在class上
    • Spring 中的 設定用註解 ,表示這個class是用來設定Spring用的
  • @Bean

    • 只能加在 帶有@Configuration的class,的方法上
    • 用途是,在Spring容器中創建一個Bean
    • 透過 @Bean 所創建的Bean,就是方法的返回值(就是下面的程式碼中,返回的HpPrinter物件,而名字則是方法的名字myPrinter)
    • 如果 寫成 @Bean(“xxx”) 的話,那bean的名字就會優先使用xxx而不是方法名 myPrinter
      1
      2
      3
      4
      5
      6
      7
      8
      @Configuration
      public class MyConfiguration{

      @Bean
      public Printer myPrinter(){
      return new HpPrinter();
      }
      }
  • Spring中,初始化bean的方法

    • 使用 @PostConstruct註解 (較常用)
    • 實現 InitializinBean interface 的 afterPropertiesSet()方法
  • @PostConstruct

    • 用途是初始化 bean
    • 加上@PostConstruct的方法, 一定要是public ,且返回值一定要是void方法也不能有參數
      1
      2
      3
      4
      @PostConstruct
      public void initialize(){
      count = 5;
      }
  • Spring Boot 設定檔-application.properties

    • 用法: 使用properties語法(key = value)
    • 用途: 存放Spring Boot 的設定值
  • @Value

    • 用法:加在Bean 或是 設定Spring用的class裡面的變數上
    • 用途:讀取Spring Boot 設定檔(application.properties)中,指定的key的值
    • @Value可以設定預設值,寫法是 @Value(“${my.name:John}”) ,這樣如果在Spring設定檔中找不到key,就會帶入預設值John
1
2
3
4
5
6
@Component
public class MyBean{

@Value("${my.name}")
private String name;
}