傳統 Spring 需在 XML 中聲明 `
| 註解 | 語意層級 | 適用場景 |
|---|---|---|
| @Component | 通用元件 | 難以歸類的通用類別 |
| @Repository | 資料存取層 (DAO) | 資料庫操作類別,可自動轉換 SQL 異常 |
| @Service | 業務邏輯層 | 核心業務處理,語意最明確 |
| @Controller | 表現層 | 處理 HTTP 請求,配合 @RequestMapping |
四者本質相同(均繼承 `@Component`),但語意化分層有助於程式碼閱讀與 AOP 切點精準匹配。
public interface TestBiz {
String getTest(String str);
}
@Component // 或 @Service
public class TestBizImp implements TestBiz {
@Override
public String getTest(String str) {
return "Return value is: " + str;
}
}
@Controller
public class TestController {
@Autowired // 欄位注入(最常用)
private TestBiz testBiz;
@RequestMapping("/getTest")
@ResponseBody
public String getTest(String str) {
return testBiz.getTest(str);
}
}
// 建構子注入(推薦:不可變、易測試)
@Autowired
public TestController(TestBiz testBiz) {
this.testBiz = testBiz;
}
// Setter 注入
@Autowired
public void setTestBiz(TestBiz testBiz) {
this.testBiz = testBiz;
}

啟動專案,訪問 https://localhost:8080/getTest?str=hello,回傳 Return value is: hello,證明依賴注入成功。
// 多實作時指定名稱
@Autowired
@Qualifier("testBizImp")
private TestBiz testBiz;
// 條件裝配:僅在特定環境生效
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public TestBiz testBiz() { return new TestBizImp(); }
Spring Boot 的依賴注入不只是語法糖,更是「配置即程式碼」哲學的體現。善用建構子注入 + `final` 欄位,能寫出更穩健、可測試的程式碼。