
摘要本文系統整理了 Spring 框架及其相關生態Spring Boot、Spring MVC、JPA 等中的常用注解按照功能分類進行詳細說明幫助開發者快速查閱和理解各個注解的作用和用法。一、Bean 聲明與注入1.1 聲明 Bean 的注解Component通用組件注解沒有明確的角色Service在業務邏輯層Service 層使用Repository在數據訪問層DAO 層使用Controller在展現層Spring MVC使用1.2 注入 Bean 的注解AutowiredSpring 提供的自動裝配注解InjectJSR-330 提供的依賴注入注解ResourceJSR-250 提供的資源注入注解1.3 Bean 生命周期與作用域Bean注解在方法上聲明當前方法的返回值為一個 BeanBean(initMethodinit, destroyMethodcleanup)指定初始化和銷毀方法Scope定義 Bean 的作用域如 Scope(prototype) 聲明為原型模式PostConstruct在構造函數執行完之后執行PreDestroy在 Bean 銷毀之前執行二、配置與屬性2.1 配置類注解Configuration聲明當前類為配置類相當于 Spring 的 XML 配置文件ComponentScan自動掃描指定包下的 Component、Service、Repository、Controller 類并注冊為 BeanWiselyConfiguration組合注解可替代 Configuration 和 ComponentScanImport導入其他配置類ImportResource加載 XML 配置文件ContextConfiguration加載配置文件如 ContextConfiguration(classes {TestConfig.class})WebAppConfiguration指定加載的 ApplicationContext 是 WebApplicationContext2.2 屬性注入與配置Value屬性注入Value(普通字符串)普通字符串注入Value(#{systemProperties[os.name]})注入操作系統屬性Value(#{ T(java.lang.Math).random() * 100.0 })注入表達式結果Value(#{demoService.another})注入其他 Bean 屬性Value(classpath:com/example/test.txt)注入文件資源Value(http://www.example.com)注入網址資源Value(${book.name})注入配置文件屬性使用 $ 符號ConfigurationProperties將 properties 屬性和 Bean 關聯實現類型安全配置EnableConfigurationProperties開啟對 ConfigurationProperties 注解配置 Bean 的支持2.3 環境配置Profile為不同環境使用不同的配置如 Profile(dev)ActiveProfiles聲明活動的 profileConditional條件注解根據特定條件創建特定的 Bean三、AOP 與事務3.1 AOP 切面編程Aspect聲明這是一個切面After、Before、Around定義切面可直接將攔截規則作為參數PointCut專門定義攔截規則然后在 After、Before、Around 中調用EnableAspectJAutoProxy開啟 Spring 對 AspectJ 切面的支持3.2 事務管理Transactional聲明式事務處理EnableTransactionManagement開啟對注解式事務的支持四、緩存與調度4.1 緩存注解Cacheable數據緩存EnableCaching開啟注解式緩存的支持4.2 異步與調度Async聲明這是一個異步任務可在類級別和方法級別聲明EnableAsync開啟異步任務支持多線程Scheduled聲明這是一個計劃任務支持 cron、fixedDelay、fixedRateEnableScheduling開啟對計劃任務的支持定時器五、Spring MVC 注解5.1 控制器相關Controller聲明類為 Spring MVC 控制器RestControllerController ResponseBody 組合注解ControllerAdvice全局控制器配置ExceptionHandler全局異常處理如 ExceptionHandler(valueException.class)5.2 請求映射與參數處理RequestMapping映射 WEB 請求訪問路徑和參數ResponseBody將返回值放入 response 體內而不是返回頁面RequestBody允許 request 參數在 request 體中PathVariable接收路徑參數如 /test/{id}ModelAttribute綁定鍵值對到 Model 中InitBinder設置 WebDataBinder自動綁定前臺請求參數到 Model六、Spring Boot 核心注解SpringBootApplicationSpring Boot 項目的核心注解組合了 Configuration、EnableAutoConfiguration 和 ComponentScanEnableAutoConfiguration讓 Spring Boot 根據依賴自動配置 Spring 框架EnableAutoConfiguration(exclude{xxx.class})禁用特定的自動配置七、數據持久化JPA注解7.1 實體映射Entity映射數據庫實體類Table指定表名如 Table(name S_PRODUCEINFO)Id聲明主鍵 IDColumn映射數據庫字段如 Column(name app_name, unique true, length 50)7.2 字段映射Enumerated枚舉類型映射如 Enumerated(EnumType.STRING)Temporal時間格式映射Temporal(TemporalType.TIMESTAMP)完整日期時間Temporal(TemporalType.DATE)年月日Temporal(TemporalType.TIME)時分秒CreationTimestamp創建時間自動填充UpdateTimestamp更新時間自動填充7.3 數據訪問EnableJpaRepositories開啟對 Spring Data JPA Repository 的支持八、測試相關注解RunWith測試運行器RunWith(JUnit4.class)使用 JUnit4 運行RunWith(SpringJUnit4ClassRunner.class)在 Spring 測試環境中運行RunWith(Suite.class)測試套件Before在測試方法前初始化九、其他實用注解9.1 Enable* 注解集合EnableWebMVC開啟對 Web MVC 的配置支持EnableDiscoveryClient讓服務發現服務器Spring Cloud 服務發現EnableEurekaServer注冊服務器Spring Cloud 服務注冊9.2 警告抑制SuppressWarnings(unchecked)忽略 unchecked 警告SuppressWarnings(serial)忽略 serializable 類缺少 serialVersionUID 警告SuppressWarnings(deprecation)忽略使用已棄用方法的警告SuppressWarnings({unchecked, deprecation})同時忽略多種警告十、綜合示例Entity Table(name S_PRODUCEINFO) Data NoArgsConstructor AllArgsConstructor public class ProduceInfoEntity { Id Column(name app_name, unique true, length 50) private String name; Column(name status) Enumerated(EnumType.STRING) private ProduceStatus status; Column(name create_time, updatable false) Temporal(TemporalType.TIMESTAMP) CreationTimestamp private Date createTime; Column(name update_time) Temporal(TemporalType.TIMESTAMP) UpdateTimestamp private Date updateTime; }注解說明Entity映射數據庫實體類Table(name S_PRODUCEINFO)指定表名Id聲明主鍵 IDColumn對應數據庫字段及屬性Enumerated(EnumType.STRING)采用枚舉值類型和數據庫字段交互Temporal時間格式映射獲取規定格式的日期CreationTimestamp創建時間自動填充UpdateTimestamp更新時間自動填充