Bean 的創建方法
-
在class上加上 @Component 註解
-
使用 @Configuration +@Bean 註解
Spring 啟用的步驟
-
按下播放建 啟動 Spring Boot
-
Spring 去檢查 class上的註解
- class上有 @Component 的註解 → 創建Bean xxxx
- class上有 @Configuration 的註解 → 設定Spring
- class上甚麼註解都沒有 → 普通class 沒有作用
-
運行
@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
-
@Bean 一定要加在帶有 @Configuration 的 class 裡面 ,這個 @Bean 的註解才會生效
-
由 @Bean 註解所生成的這個 bean ,所生成的 bean 就是方法返回的 object -> Printer myPrinter = 方法返回的 object
-
Bean 的名字預設會是方法名 -> Printer myPrinter = new HpPrinter();
-
@Bean(”xxx”) 註解裡有字串 ,就會優先當作 bean 的名字 -> Printer xxx= new HpPrinter();

練習
先把 @Component 的註解都先去掉
然後創個 class 名字可以隨意 ,我這邊取 MyConfiguration
@Bean 會 return hpPrinter 也就是 Printer myPrinter = new HpPrinter();

在網址上輸入 localhost:8080/test
console: