天天看點

接近8000字的Spring/SpringBoot常用注解總結!安排!

0.前言

大家好,我是 Guide 哥!這是我的 221 篇優質原創文章。如需轉載,請在文首注明位址,蟹蟹!

本文已經收錄進我的 75K Star 的 Java 開源項目 JavaGuide:

https://github.com/Snailclimb/JavaGuide

可以毫不誇張地說,這篇文章介紹的 Spring/SpringBoot 常用注解基本已經涵蓋你工作中遇到的大部分常用的場景。對于每一個注解我都說了具體用法,掌握搞懂,使用 SpringBoot 來開發項目基本沒啥大問題了!

整個目錄如下,内容有點多:

為什麼要寫這篇文章?

最近看到網上有一篇關于 SpringBoot 常用注解的文章被轉載的比較多,我看了文章内容之後屬實覺得品質有點低,并且有點會誤導沒有太多實際使用經驗的人(這些人又占據了大多數)。是以,自己索性花了大概 兩天時間簡單總結一下了。

因為我個人的能力和精力有限,如果有任何不對或者需要完善的地方,請幫忙指出!Guide 哥感激不盡!

1.

@SpringBootApplication

這裡先單獨拎出

@SpringBootApplication

注解說一下,雖然我們一般不會主動去使用它。

Guide 哥:這個注解是 Spring Boot 項目的基石,建立 SpringBoot 項目之後會預設在主類加上。

@SpringBootApplication
public class SpringSecurityJwtGuideApplication {
      public static void main(java.lang.String[] args) {
        SpringApplication.run(SpringSecurityJwtGuideApplication.class, args);
    }
}           

我們可以把

@SpringBootApplication

看作是

@Configuration

@EnableAutoConfiguration

@ComponentScan

注解的集合。

package org.springframework.boot.autoconfigure;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
   ......
}

package org.springframework.boot;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}           

根據 SpringBoot 官網,這三個注解的作用分别是:

  • @EnableAutoConfiguration

    :啟用 SpringBoot 的自動配置機制
  • @ComponentScan

    : 掃描被

    @Component

    (

    @Service

    ,

    @Controller

    )注解的 bean,注解預設會掃描該類所在的包下所有的類。
  • @Configuration

    :允許在 Spring 上下文中注冊額外的 bean 或導入其他配置類

2. Spring Bean 相關

2.1.

@Autowired

自動導入對象到類中,被注入進的類同樣要被 Spring 容器管理比如:Service 類注入到 Controller 類中。

@Service
public class UserService {
  ......
}

@RestController
@RequestMapping("/users")
public class UserController {
   @Autowired
   private UserService userService;
   ......
}           

2.2.

Component

@Repository

@Service

@Controller

我們一般使用

@Autowired

注解讓 Spring 容器幫我們自動裝配 bean。要想把類辨別成可用于

@Autowired

注解自動裝配的 bean 的類,可以采用以下注解實作:

  • @Component

    :通用的注解,可标注任意類為

    Spring

    元件。如果一個 Bean 不知道屬于哪個層,可以使用

    @Component

    注解标注。
  • @Repository

    : 對應持久層即 Dao 層,主要用于資料庫相關操作。
  • @Service

    : 對應服務層,主要涉及一些複雜的邏輯,需要用到 Dao 層。
  • @Controller

    : 對應 Spring MVC 控制層,主要使用者接受使用者請求并調用 Service 層傳回資料給前端頁面。

2.3.

@RestController

@RestController

注解是

@Controller和

@

ResponseBody

的合集,表示這是個控制器 bean,并且是将函數的傳回值直 接填入 HTTP 響應體中,是 REST 風格的控制器。

Guide 哥:現在都是前後端分離,說實話我已經很久沒有用過

@Controller

。如果你的項目太老了的話,就當我沒說。

單獨使用

@Controller

不加

@ResponseBody

的話一般使用在要傳回一個視圖的情況,這種情況屬于比較傳統的 Spring MVC 的應用,對應于前後端不分離的情況。

@Controller

+

@ResponseBody

傳回 JSON 或 XML 形式資料

關于

@RestController

@Controller

的對比,請看這篇文章:

@RestController vs @Controller

2.4.

@Scope

聲明 Spring Bean 的作用域,使用方法:

@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}           

四種常見的 Spring Bean 的作用域:

  • singleton : 唯一 bean 執行個體,Spring 中的 bean 預設都是單例的。
  • prototype : 每次請求都會建立一個新的 bean 執行個體。
  • request : 每一次 HTTP 請求都會産生一個新的 bean,該 bean 僅在目前 HTTP request 内有效。
  • session : 每一次 HTTP 請求都會産生一個新的 bean,該 bean 僅在目前 HTTP session 内有效。

2.5.

Configuration

一般用來聲明配置類,可以使用

@Component

注解替代,不過使用

Configuration

注解聲明配置類更加語義化。

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}           

3. 處理常見的 HTTP 請求類型

5 種常見的請求類型:

  • GET :請求從伺服器擷取特定資源。舉個例子:

    GET /users

    (擷取所有學生)
  • POST :在伺服器上建立一個新的資源。舉個例子:

    POST /users

    (建立學生)
  • PUT :更新伺服器上的資源(用戶端提供更新後的整個資源)。舉個例子:

    PUT /users/12

    (更新編号為 12 的學生)
  • DELETE :從伺服器删除特定的資源。舉個例子:

    DELETE /users/12

    (删除編号為 12 的學生)
  • PATCH :更新伺服器上的資源(用戶端提供更改的屬性,可以看做作是部分更新),使用的比較少,這裡就不舉例子了。

3.1. GET 請求

@GetMapping("users")

等價于

@RequestMapping(value="/users",method=RequestMethod.GET)

@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
 return userRepository.findAll();
}           

3.2. POST 請求

@PostMapping("users")

@RequestMapping(value="/users",method=RequestMethod.POST)

@RequestBody

注解的使用,在下面的“前後端傳值”這塊會講到。

@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) {
 return userRespository.save(user);
}           

3.3. PUT 請求

@PutMapping("/users/{userId}")

@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)

@PutMapping("/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId,
  @Valid @RequestBody UserUpdateRequest userUpdateRequest) {
  ......
}           

3.4. DELETE 請求

@DeleteMapping("/users/{userId}")

@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)

@DeleteMapping("/users/{userId}")
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){
  ......
}           

3.5. PATCH 請求

一般實際項目中,我們都是 PUT 不夠用了之後才用 PATCH 請求去更新資料。

@PatchMapping("/profile")
  public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) {
        studentRepository.updateDetail(studentUpdateRequest);
        return ResponseEntity.ok().build();
    }           

4. 前後端傳值

掌握前後端傳值的正确姿勢,是你開始 CRUD 的第一步!

4.1.

@PathVariable

@RequestParam

@PathVariable

用于擷取路徑參數,

@RequestParam

用于擷取查詢參數。

舉個簡單的例子:

@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(
         @PathVariable("klassId") Long klassId,
         @RequestParam(value = "type", required = false) String type ) {
...
}           

如果我們請求的 url 是:

/klasses/{123456}/teachers?type=web

那麼我們服務擷取到的資料就是:

klassId=123456,type=web

4.2.

@RequestBody

用于讀取 Request 請求(可能是 POST,PUT,DELETE,GET 請求)的 body 部分并且Content-Type 為 application/json 格式的資料,接收到資料之後會自動将資料綁定到 Java 對象上去。系統會使用

HttpMessageConverter

或者自定義的

HttpMessageConverter

将請求的 body 中的 json 字元串轉換為 java 對象。

我用一個簡單的例子來給示範一下基本使用!

我們有一個注冊的接口:

@PostMapping("/sign-up")
public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
  userService.save(userRegisterRequest);
  return ResponseEntity.ok().build();
}           

UserRegisterRequest

對象:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegisterRequest {
    @NotBlank
    private String userName;
    @NotBlank
    private String password;
    @FullName
    @NotBlank
    private String fullName;
}           

我們發送 post 請求到這個接口,并且 body 攜帶 JSON 資料:

{"userName":"coder","fullName":"shuangkou","password":"123456"}           

這樣我們的後端就可以直接把 json 格式的資料映射到我們的

UserRegisterRequest

類上。

👉 需要注意的是:一個請求方法隻可以有一個

@RequestBody

,但是可以有多個

@RequestParam

@PathVariable

。 如果你的方法必須要用兩個

@RequestBody

來接受資料的話,大機率是你的資料庫設計或者系統設計出問題了!

5. 讀取配置資訊

很多時候我們需要将一些常用的配置資訊比如阿裡雲 oss、發送短信、微信認證的相關配置資訊等等放到配置檔案中。

下面我們來看一下 Spring 為我們提供了哪些方式幫助我們從配置檔案中讀取這些配置資訊。

我們的資料源

application.yml

内容如下::

wuhan2020: 2020年初武漢爆發了新型冠狀病毒,疫情嚴重,但是,我相信一切都會過去!武漢加油!中國加油!

my-profile:
  name: Guide哥
  email: [email protected]

library:
  location: 湖北武漢加油中國加油
  books:
    - name: 天才基本法
      description: 二十二歲的林朝夕在父親确診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即将出國深造的消息——對方考取的學校,恰是父親當年為她放棄的那所。
    - name: 時間的秩序
      description: 為什麼我們記得過去,而非未來?時間“流逝”意味着什麼?是我們存在于時間之内,還是時間存在于我們之中?卡洛·羅韋利用詩意的文字,邀請我們思考這一亘古難題——時間的本質。
    - name: 了不起的我
      description: 如何養成一個新習慣?如何讓心智變得更成熟?如何擁有高品質的關系? 如何走出人生的艱難時刻?           

5.1.

@value

(常用)

使用

@Value("${property}")

讀取比較簡單的配置資訊:

@Value("${wuhan2020}")
String wuhan2020;           

5.2.

@ConfigurationProperties

通過

@ConfigurationProperties

讀取配置資訊并與 bean 綁定。

@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {
    @NotEmpty
    private String location;
    private List<Book> books;

    @Setter
    @Getter
    @ToString
    static class Book {
        String name;
        String description;
    }
  省略getter/setter
  ......
}           

你可以像使用普通的 Spring bean 一樣,将其注入到類中使用。

5.3.

PropertySource

(不常用)

@PropertySource

讀取指定 properties 檔案

@Component
@PropertySource("classpath:website.properties")

class WebSite {
    @Value("${url}")
    private String url;

  省略getter/setter
  ......
}           

更多内容請檢視我的這篇文章:《

10 分鐘搞定 SpringBoot 如何優雅讀取配置檔案?

》 。

6. 參數校驗

資料的校驗的重要性就不用說了,即使在前端對資料進行校驗的情況下,我們還是要對傳入後端的資料再進行一遍校驗,避免使用者繞過浏覽器直接通過一些 HTTP 工具直接向後端請求一些違法資料。

JSR(Java Specification Requests) 是一套 JavaBean 參數校驗的标準,它定義了很多常用的校驗注解,我們可以直接将這些注解加在我們 JavaBean 的屬性上面,這樣就可以在需要校驗的時候進行校驗了,非常友善!

校驗的時候我們實際用的是 Hibernate Validator 架構。Hibernate Validator 是 Hibernate 團隊最初的資料校驗架構,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的參考實作,Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的參考實作,目前最新版的 Hibernate Validator 6.x 是 Bean Validation 2.0(JSR 380)的參考實作。

SpringBoot 項目的 spring-boot-starter-web 依賴中已經有 hibernate-validator 包,不需要引用相關依賴。如下圖所示(通過 idea 插件—Maven Helper 生成):

非 SpringBoot 項目需要自行引入相關依賴包,這裡不多做講解,具體可以檢視我的這篇文章:《

如何在 Spring/Spring Boot 中做參數校驗?你需要了解的都在這裡!

》。

👉 需要注意的是: 所有的注解,推薦使用 JSR 注解,即

javax.validation.constraints

,而不是

org.hibernate.validator.constraints

6.1. 一些常用的字段驗證的注解

  • @NotEmpty

    被注釋的字元串的不能為 null 也不能為空
  • @NotBlank

    被注釋的字元串非 null,并且必須包含一個非空白字元
  • @Null

    被注釋的元素必須為 null
  • @NotNull

    被注釋的元素必須不為 null
  • @AssertTrue

    被注釋的元素必須為 true
  • @AssertFalse

    被注釋的元素必須為 false
  • @Pattern(regex=,flag=)

    被注釋的元素必須符合指定的正規表達式
  • @Email

    被注釋的元素必須是 Email 格式。
  • @Min(value)

    被注釋的元素必須是一個數字,其值必須大于等于指定的最小值
  • @Max(value)

    被注釋的元素必須是一個數字,其值必須小于等于指定的最大值
  • @DecimalMin(value)

  • @DecimalMax(value)

  • @Size(max=, min=)

    被注釋的元素的大小必須在指定的範圍内
  • @Digits (integer, fraction)

    被注釋的元素必須是一個數字,其值必須在可接受的範圍内
  • @Past

    被注釋的元素必須是一個過去的日期
  • @Future

    被注釋的元素必須是一個将來的日期
  • ......

6.2. 驗證請求體(RequestBody)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    @NotNull(message = "classId 不能為空")
    private String classId;

    @Size(max = 33)
    @NotNull(message = "name 不能為空")
    private String name;

    @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可選範圍")
    @NotNull(message = "sex 不能為空")
    private String sex;

    @Email(message = "email 格式不正确")
    @NotNull(message = "email 不能為空")
    private String email;

}           

我們在需要驗證的參數上加上了

@Valid

注解,如果驗證失敗,它将抛出

MethodArgumentNotValidException

@RestController
@RequestMapping("/api")
public class PersonController {

    @PostMapping("/person")
    public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) {
        return ResponseEntity.ok().body(person);
    }
}           

6.3. 驗證請求參數(Path Variables 和 Request Parameters)

一定一定不要忘記在類上加上

Validated

注解了,這個參數可以告訴 Spring 去校驗方法參數。

@RestController
@RequestMapping("/api")
@Validated
public class PersonController {

    @GetMapping("/person/{id}")
    public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超過 id 的範圍了") Integer id) {
        return ResponseEntity.ok().body(id);
    }
}           

更多關于如何在 Spring 項目中進行參數校驗的内容,請看《

》這篇文章。

7. 全局處理 Controller 層異常

介紹一下我們 Spring 項目必備的全局處理 Controller 層異常。

相關注解:

  1. @ControllerAdvice

    :注解定義全局異常處理類
  2. @ExceptionHandler

    :注解聲明異常處理方法

如何使用呢?拿我們在第 5 節參數校驗這塊來舉例子。如果方法參數不對的話就會抛出

MethodArgumentNotValidException

,我們來處理這個異常。

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 請求參數異常處理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
       ......
    }
}           

更多關于 Spring Boot 異常處理的内容,請看我的這兩篇文章:

  1. SpringBoot 處理異常的幾種常見姿勢
  2. 使用枚舉簡單封裝一個優雅的 Spring Boot 全局異常處理!

8. JPA 相關

8.1. 建立表

@Entity

聲明一個類對應一個資料庫實體。

@Table

設定表明

@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    省略getter/setter......
}           

8.2. 建立主鍵

@Id

:聲明一個字段為主鍵。

@Id

聲明之後,我們還需要定義主鍵的生成政策。我們可以使用

@GeneratedValue

指定主鍵生成政策。

1.通過

@GeneratedValue

直接使用 JPA 内置提供的四種主鍵生成政策來指定主鍵生成政策。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;           

JPA 使用枚舉定義了 4 中常見的主鍵生成政策,如下:

Guide 哥:枚舉替代常量的一種用法

public enum GenerationType {

    /**
     * 使用一個特定的資料庫表格來儲存主鍵
     * 持久化引擎通過關系資料庫的一張特定的表格來生成主鍵,
     */
    TABLE,

    /**
     *在某些資料庫中,不支援主鍵自增長,比如Oracle、PostgreSQL其提供了一種叫做"序列(sequence)"的機制生成主鍵
     */
    SEQUENCE,

    /**
     * 主鍵自增長
     */
    IDENTITY,

    /**
     *把主鍵生成政策交給持久化引擎(persistence engine),
     *持久化引擎會根據資料庫在以上三種主鍵生成 政策中選擇其中一種
     */
    AUTO
}
           

@GeneratedValue

注解預設使用的政策是

GenerationType.AUTO

public @interface GeneratedValue {

    GenerationType strategy() default AUTO;
    String generator() default "";
}           

一般使用 MySQL 資料庫的話,使用

GenerationType.IDENTITY

政策比較普遍一點(分布式系統的話需要另外考慮使用分布式 ID)。

2.通過

@GenericGenerator

聲明一個主鍵政策,然後

@GeneratedValue

使用這個政策

@Id
@GeneratedValue(generator = "IdentityIdGenerator")
@GenericGenerator(name = "IdentityIdGenerator", strategy = "identity")
private Long id;           

等價于:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;           

jpa 提供的主鍵生成政策有如下幾種:

public class DefaultIdentifierGeneratorFactory
        implements MutableIdentifierGeneratorFactory, Serializable, ServiceRegistryAwareService {

    @SuppressWarnings("deprecation")
    public DefaultIdentifierGeneratorFactory() {
        register( "uuid2", UUIDGenerator.class );
        register( "guid", GUIDGenerator.class );            // can be done with UUIDGenerator + strategy
        register( "uuid", UUIDHexGenerator.class );            // "deprecated" for new use
        register( "uuid.hex", UUIDHexGenerator.class );     // uuid.hex is deprecated
        register( "assigned", Assigned.class );
        register( "identity", IdentityGenerator.class );
        register( "select", SelectGenerator.class );
        register( "sequence", SequenceStyleGenerator.class );
        register( "seqhilo", SequenceHiLoGenerator.class );
        register( "increment", IncrementGenerator.class );
        register( "foreign", ForeignGenerator.class );
        register( "sequence-identity", SequenceIdentityGenerator.class );
        register( "enhanced-sequence", SequenceStyleGenerator.class );
        register( "enhanced-table", TableGenerator.class );
    }

    public void register(String strategy, Class generatorClass) {
        LOG.debugf( "Registering IdentifierGenerator strategy [%s] -> [%s]", strategy, generatorClass.getName() );
        final Class previous = generatorStrategyToClassNameMap.put( strategy, generatorClass );
        if ( previous != null ) {
            LOG.debugf( "    - overriding [%s]", previous.getName() );
        }
    }

}           

8.3. 設定字段類型

@Column

聲明字段。

示例:

設定屬性 userName 對應的資料庫字段名為 user_name,長度為 32,非空

@Column(name = "user_name", nullable = false, length=32)
private String userName;           

設定字段類型并且加預設值,這個還是挺常用的。

Column(columnDefinition = "tinyint(1) default 1")
private Boolean enabled;           

8.4. 指定不持久化特定字段

@Transient

:聲明不需要與資料庫映射的字段,在儲存的時候不需要儲存進資料庫 。

如果我們想讓

secrect

這個字段不被持久化,可以使用

@Transient

關鍵字聲明。

Entity(name="USER")
public class User {

    ......
    @Transient
    private String secrect; // not persistent because of @Transient

}           

除了

@Transient

關鍵字聲明, 還可以采用下面幾種方法:

static String secrect; // not persistent because of static
final String secrect = “Satish”; // not persistent because of final
transient String secrect; // not persistent because of transient           

一般使用注解的方式比較多。

8.5. 聲明大字段

@Lob

:聲明某個字段為大字段。

@Lob
private String content;           

更詳細的聲明:

@Lob
//指定 Lob 類型資料的擷取政策, FetchType.EAGER 表示非延遲 加載,而 FetchType. LAZY 表示延遲加載 ;
@Basic(fetch = FetchType.EAGER)
//columnDefinition 屬性指定資料表對應的 Lob 字段類型
@Column(name = "content", columnDefinition = "LONGTEXT NOT NULL")
private String content;           

8.6. 建立枚舉類型的字段

可以使用枚舉類型的字段,不過枚舉字段要用

@Enumerated

注解修飾。

public enum Gender {
    MALE("男性"),
    FEMALE("女性");

    private String value;
    Gender(String str){
        value=str;
    }
}           
@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    @Enumerated(EnumType.STRING)
    private Gender gender;
    省略getter/setter......
}           

資料庫裡面對應存儲的是 MAIL/FEMAIL。

8.7. 增加審計功能

隻要繼承了

AbstractAuditBase

的類都會預設加上下面四個字段。

@Data
@AllArgsConstructor
@NoArgsConstructor
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public abstract class AbstractAuditBase {

    @CreatedDate
    @Column(updatable = false)
    @JsonIgnore
    private Instant createdAt;

    @LastModifiedDate
    @JsonIgnore
    private Instant updatedAt;

    @CreatedBy
    @Column(updatable = false)
    @JsonIgnore
    private String createdBy;

    @LastModifiedBy
    @JsonIgnore
    private String updatedBy;
}
           

我們對應的審計功能對應地配置類可能是下面這樣的(Spring Security 項目):

@Configuration
@EnableJpaAuditing
public class AuditSecurityConfiguration {
    @Bean
    AuditorAware<String> auditorAware() {
        return () -> Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .filter(Authentication::isAuthenticated)
                .map(Authentication::getName);
    }
}           

簡單介紹一下上面設計到的一些注解:

  1. @CreatedDate

    : 表示該字段為建立時間時間字段,在這個實體被 insert 的時候,會設定值
  2. @CreatedBy

    :表示該字段為建立人,在這個實體被 insert 的時候,會設定值

@LastModifiedDate

@LastModifiedBy

同理。

@EnableJpaAuditing

:開啟 JPA 審計功能。

8.8. 删除/修改資料

@Modifying

注解提示 JPA 該操作是修改操作,注意還要配合

@Transactional

注解使用。

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    void deleteByUserName(String userName);
}           

8.9. 關聯關系

  • @OneToOne

    聲明一對一關系
  • @OneToMany

    聲明一對多關系
  • @ManyToOne

    聲明多對一關系
  • MangToMang

    聲明多對多關系

更多關于 Spring Boot JPA 的文章請看我的這篇文章:

一文搞懂如何在 Spring Boot 正确中使用 JPA

9. 事務

@Transactional

在要開啟事務的方法上使用

@Transactional

注解即可!

@Transactional(rollbackFor = Exception.class)
public void save() {
  ......
}
           

我們知道 Exception 分為運作時異常 RuntimeException 和非運作時異常。在

@Transactional

注解中如果不配置

rollbackFor

屬性,那麼事物隻會在遇到

RuntimeException

的時候才會復原,加上

rollbackFor=Exception.class

,可以讓事物在遇到非運作時異常時也復原。

@Transactional

注解一般用在可以作用在

或者

方法

上。

  • 作用于類:當把

    @Transactional 注解放在類上時,表示所有該類的

    public 方法都配置相同的事務屬性資訊。
  • 作用于方法:當類配置了

    @Transactional

    ,方法也配置了

    @Transactional

    ,方法的事務會覆寫類的事務配置資訊。

更多關于關于 Spring 事務的内容請檢視:

  1. 可能是最漂亮的 Spring 事務管理詳解
  2. 一口氣說出 6 種 @Transactional 注解失效場景

10. json 資料處理

10.1. 過濾 json 資料

@JsonIgnoreProperties

作用在類上用于過濾掉特定字段不傳回或者不解析。

//生成json時将userRoles屬性過濾
@JsonIgnoreProperties({"userRoles"})
public class User {

    private String userName;
    private String fullName;
    private String password;
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}           

@JsonIgnore

一般用于類的屬性上,作用和上面的

@JsonIgnoreProperties

一樣。

public class User {

    private String userName;
    private String fullName;
    private String password;
   //生成json時将userRoles屬性過濾
    @JsonIgnore
    private List<UserRole> userRoles = new ArrayList<>();
}           

10.2. 格式化 json 資料

@JsonFormat

一般用來格式化 json 資料。:

比如:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT")
private Date date;           

10.3. 扁平化對象

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;

  @Getter
  @Setter
  @ToString
  public static class Location {
     private String provinceName;
     private String countyName;
  }
  @Getter
  @Setter
  @ToString
  public static class PersonInfo {
    private String userName;
    private String fullName;
  }
}
           

未扁平化之前:

{
    "location": {
        "provinceName":"湖北",
        "countyName":"武漢"
    },
    "personInfo": {
        "userName": "coder1234",
        "fullName": "shaungkou"
    }
}           

@JsonUnwrapped

扁平對象之後:

@Getter
@Setter
@ToString
public class Account {
    @JsonUnwrapped
    private Location location;
    @JsonUnwrapped
    private PersonInfo personInfo;
    ......
}           
{
  "provinceName":"湖北",
  "countyName":"武漢",
  "userName": "coder1234",
  "fullName": "shaungkou"
}           

11. 測試相關

@ActiveProfiles

一般作用于測試類上, 用于聲明生效的 Spring 配置檔案。

@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("test")
@Slf4j
public abstract class TestBase {
  ......
}           

@Test

聲明一個方法為測試方法

@Transactional

被聲明的測試方法的資料會復原,避免污染測試資料。

@WithMockUser

Spring Security 提供的,用來模拟一個真實使用者,并且可以賦予權限。

@Test
    @Transactional
    @WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER")
    void should_import_student_success() throws Exception {
        ......
    }           

暫時總結到這裡吧!雖然花了挺長時間才寫完,不過可能還是會一些常用的注解的被漏掉,是以,我将文章也同步到了 Github 上去,Github 位址:

https://github.com/Snailclimb/JavaGuide/blob/master/docs/system-design/framework/spring/spring-annotations.md

歡迎完善!