在 Spring Boot 中,最常見的創建 Bean 的方法,就是在 class 上面加上一行 @Component
的程式。只要在 class 上面加上一行 @Component
之後,就可以將這樣 class 變成一個 Bean 了。
@Component
public class HpPrinter implements Printer {
//....
}
要注入 Bean 也很簡單,只需要在變數上面加上 @Autowired
這行程式,就可以將 Spring 容器中的 Bean 給注入進來了。
@Component
public class Teacher {
@Autowired
private Printer printer;
}
講到@RestController時可以看原碼,它又有個標註@Controller
而@Controller的原碼中又有個標註@Component
所以@RestController自然也是@Component
噢噢感謝補充!確實 @RestController 就是因為自帶 @Component,所以他才能成為一個 Bean 沒錯XD(文章中因為篇幅關係,所以沒有特別展開這邊的介紹,感謝補充~)
您好,我想請問HpPrinter是因為有 implements Printer 這個interface,在變成 Bean 之後才能被視別為一種Printer,然後透過在MyController這個Class 中 @Autowired注入的嗎?
對的唷!完全正確!
這裡就是利用到了 「Java 的多型 (polymorphism)」的特性,所以才可以將 HpPrinter 的類型,轉換成 Printer 這個類型
好的了解,謝謝您的回覆!