想用註解替換 XML 中的 `
Spring 提供四大核心註解,按語義分層:
| 註解 | 用途 | 語義層級 |
|---|---|---|
| @Component | 通用組件,無特定業務含義 | 基礎 |
| @Repository | 數據訪問層(DAO) | 持久層 |
| @Service | 業務邏輯層 | 服務層 |
| @Controller | 控制層(Spring MVC) | 表現層 |
對於 `ContentDao`,應使用 @Repository:
@Repository("contentDao")
public class ContentDao { }
僅加註解不夠,必須在 XML 配置掃描包路徑:
<!-- applicationContext.xml -->
<context:component-scan base-package="com.itschool" />
或 Java 配置類:
@Configuration
@ComponentScan("com.itschool")
public class AppConfig { }
@Repository("myContentDao") // 指定 bean 名稱,默認類名首字母小寫
@Scope("prototype") // 默認 singleton,可改為 prototype
public class ContentDao { }