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