跳转至

Bean 的創建方法

  1. 在class上加上 @Component 註解

  2. 使用 @Configuration +@Bean 註解

Spring 啟用的步驟

  1. 按下播放建 啟動 Spring Boot

  2. Spring 去檢查 class上的註解

    1. class上有 @Component 的註解 → 創建Bean xxxx
    2. class上有 @Configuration 的註解 → 設定Spring
    3. class上甚麼註解都沒有 → 普通class 沒有作用
  3. 運行

@Component 與 @Configuration

@Component 將此 class 變成一個由 Spring 容器所管理的bean

@Configuration 將此 class 變成設定 Spring 用的 class

@Configuration 設定用註解 ,表示這個 class 是拿來設定Spring 用的

@Configuration
public class MyConfiguration{ 
    @Bean // @Bean 在Spring創建一個Bean myPrinter
    public Printer myPrinter(){
        return new HpPrinter(); // 回傳一個hpPrinter 的object
    }
}

// Printer myPrinter = 方法返回的object
// 也就是 Printer myPrinter = new HpPrinter();

@Bean

  1. @Bean 一定要加在帶有 @Configuration 的 class 裡面 ,這個 @Bean 的註解才會生效

  2. 由 @Bean 註解所生成的這個 bean ,所生成的 bean 就是方法返回的 object -> Printer myPrinter = 方法返回的 object

  3. Bean 的名字預設會是方法名 -> Printer myPrinter = new HpPrinter();

  4. @Bean(”xxx”) 註解裡有字串 ,就會優先當作 bean 的名字 -> Printer xxx= new HpPrinter();

練習

先把 @Component 的註解都先去掉

然後創個 class 名字可以隨意 ,我這邊取 MyConfiguration

@Bean 會 return hpPrinter 也就是 Printer myPrinter = new HpPrinter();

在網址上輸入 localhost:8080/test

console:

Hp印表機: Hello