註解 可視為類/方法的擴展模板:按規則為目標標註參數,運行時通過反射獲取配置信息。
@interface MyAnnotation { String value(); int count() default 0; }@Target(ElementType.TYPE) 作用目標 (類/方法/字段等)@Retention(RetentionPolicy.RUNTIME) 保留至運行期@Documented 納入 Javadoc@Inherited 允許子類繼承@MyAnnotation(value="test", count=1) public class Demo {},反射獲取:clazz.getAnnotation(MyAnnotation.class)。


方法級註解只需將 @Target 改為 ElementType.METHOD。
| 維度 | XML 配置 | 註解 |
|---|---|---|
| OCP 原則 | ✅ 修改配置無需改代碼 | ❌ 擴展需改代碼 |
| 集中管理 | ✅ 關系清晰 | ❌ 分散在各類上 |
| 開發速度 | ❌ 較慢 | ✅ 快 |
| 編譯期檢查 | ❌ 難發現錯誤 | ✅ 易定位 |
若自定義註解 @MyComp 本身標註了 Spring 的 @Component,則使用 @MyComp 時無需再加 @Component,Spring 會遞歸識別。
@Component // 元註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComp {}
@MyComp // 等效於 @Component + @MyComp
public class MyService {}


