插件
Translation
idea的翻譯插件
安裝:Plugins直接搜索
使用:
選中文本,右鍵翻譯即可
選中文本,
Ctrl+Shift+y
調(diào)試
Stream流調(diào)試
在Stream流代碼處上打斷點
Debug模式啟動調(diào)試代碼丹弱,讓代碼運行到斷點處停止
點擊流按鈕
1645104780426.png
- 默認為split模式撰茎,點擊左下角,Flat Mpde汤求,切換模式挨稿,即可看到Stream流內(nèi)的所有執(zhí)行流程
1645104826950.png
參數(shù)校驗
validator
作用:省去繁瑣的if-else參數(shù)校驗
引入依賴
<!-- Spring Boot2.3版本以上 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
插件自帶注解
@Null 被注釋的元素必須為 null
@NotNull 被注釋的元素必須不為 null
@AssertTrue 被注釋的元素必須為 true
@AssertFalse 被注釋的元素必須為 false
@Min(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值
@Max(value) 被注釋的元素必須是一個數(shù)字蔫巩,其值必須小于等于指定的最大值
@DecimalMin(value) 被注釋的元素必須是一個數(shù)字谆棱,其值必須大于等于指定的最小值
@DecimalMax(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值
@Size(max, min) 被注釋的元素的大小必須在指定的范圍內(nèi)
@Digits (integer, fraction) 被注釋的元素必須是一個數(shù)字圆仔,其值必須在可接受的范圍內(nèi)
@Past 被注釋的元素必須是一個過去的日期
@Future 被注釋的元素必須是一個將來的日期
@Pattern(value) 被注釋的元素必須符合指定的正則表達式
使用示例
創(chuàng)建實體類
package com.example.share.entity;
import lombok.Data;
import javax.validation.constraints.*;
import java.io.Serializable;
/**
* 用戶實體類
*/
@Data
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用戶主鍵
*/
@NotNull(message = "用戶主鍵不能為Null")
private Long id;
/**
* 用戶名稱
*/
@NotBlank(message = "用戶名不能為空")
private String name;
/**
* 郵箱
*/
@NotNull(message = "郵箱不能為空")
@Email(message = "郵箱格式不正確")
private String email;
}
創(chuàng)建返回對象
package com.example.share.response;
import lombok.Data;
import java.util.List;
/**
* 自定義返回實體
*/
@Data
public class MyResponse {
/**
* 狀態(tài)碼
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 多條錯誤信息
*/
private List<String> errorMessageList;
public MyResponse(){}
public MyResponse(Integer code) {
this.code = code;
}
}
創(chuàng)建控制器
package com.example.share.controller;
import com.example.share.annotation.group.Create;
import com.example.share.annotation.group.Update;
import com.example.share.entity.UserEntity;
import com.example.share.response.MyResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 參數(shù)校驗測試控制器
*/
@RestController()
@RequestMapping("/paramVerification")
public class ParameterVerificationController {
/**
* 使用@Validated聲明需要檢查參數(shù)
* @param userEntity
*/
@PostMapping("/user")
public MyResponse verifyUserEntity(@RequestBody @Validated UserEntity userEntity){
System.out.println("--------------校驗用戶實體類--------------");
return new MyResponse(0);
}
}
使用postman請求接口垃瞧,如果服務(wù)器接收到的參數(shù)與實體類上注解規(guī)則不一致,則服務(wù)器內(nèi)部拋出
MethodArgumentNotValidException
異常坪郭,為統(tǒng)一返回數(shù)據(jù)个从,故創(chuàng)建一全局的異常處理類,如下
自定義全局異常處理類
package com.example.share.handler;
import com.example.share.response.MyResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
import java.util.stream.Collectors;
/**
* 自定義Controller的異常全局處理類
* 對Controller的增強
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public MyResponse parameterVerificationHandler(MethodArgumentNotValidException exception){
List<FieldError> fieldErrorList = exception.getBindingResult().getFieldErrors();
List<String> errorMessageList = fieldErrorList.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.toList());
MyResponse response = new MyResponse();
response.setCode(-1);
response.setErrorMessageList(errorMessageList);
return response;
}
}
如此歪沃,即可完成參數(shù)校驗嗦锐,如果插件自帶注解無法滿足要求,可自定義注解來滿足需求沪曙,見下文
自定義注解校驗參數(shù)
自定義注解
package com.example.share.annotation;
import com.example.share.annotation.group.Update;
import com.example.share.validator.IdentityCardNumberValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* 自定義注解
*/
// 生成javadoc的時候就會把@Documented注解給顯示出來
@Documented
// 對屬性生效
@Target({ElementType.PARAMETER, ElementType.FIELD})
// 保留多久
@Retention(RetentionPolicy.RUNTIME)
// 代表處理邏輯是IdentityCardNumberValidator類
@Constraint(validatedBy = IdentityCardNumberValidator.class)
public @interface IdentityCardNumber {
// 定制化提示信息
String message() default "身份證號碼不合法";
String text() default "text";
// 將validator進行分類奕污,不同的group中執(zhí)行不同的操作
// Class<?>[] groups() default {Update.class};
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
/**
* @Target(ElementType.TYPE)——接口、類液走、枚舉碳默、注解
* @Target(ElementType.FIELD)——字段、枚舉的常量
* @Target(ElementType.METHOD)——方法
* @Target(ElementType.PARAMETER)——方法參數(shù)
* @Target(ElementType.CONSTRUCTOR) ——構(gòu)造函數(shù)
* @Target(ElementType.LOCAL_VARIABLE)——局部變量
* @Target(ElementType.ANNOTATION_TYPE)——注解
* @Target(ElementType.PACKAGE)——包
* ————————————————
* 版權(quán)聲明:本文為CSDN博主「fengcai0123」的原創(chuàng)文章缘眶,遵循CC 4.0 BY-SA版權(quán)協(xié)議嘱根,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
* 原文鏈接:https://blog.csdn.net/fengcai0123/article/details/90544338
*
* @Retention作用是定義被它所注解的注解保留多久巷懈,一共有三種策略该抒,定義在RetentionPolicy枚舉中.
*
* 從注釋上看:
* source:注解只保留在源文件,當Java文件編譯成class文件的時候顶燕,注解被遺棄凑保;被編譯器忽略
* class:注解被保留到class文件冈爹,但jvm加載class文件時候被遺棄,這是默認的生命周期
* runtime:注解不僅被保存到class文件中愉适,jvm加載class文件之后犯助,仍然存在
*/
實現(xiàn)自定義注解的驗證邏輯
package com.example.share.validator;
import com.example.share.annotation.IdentityCardNumber;
import com.example.share.util.IDUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 驗證邏輯實現(xiàn)
*/
public class IdentityCardNumberValidator implements ConstraintValidator<IdentityCardNumber, Object> {
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
return IDUtils.isIDNumber(o.toString());
}
@Override
public void initialize(IdentityCardNumber identityCardNumber){
}
}
測試同上,該不贅述
分組校驗參數(shù)
將不同的校驗規(guī)則分給不同的組维咸,在使用時,指定不同的校驗規(guī)則
創(chuàng)建分組
package com.example.share.annotation.group;
import javax.validation.groups.Default;
/**
* 自定義分組Create
*/
public interface Create extends Default {
}
package com.example.share.annotation.group;
import javax.validation.groups.Default;
/**
* 自定義分組Update
*/
public interface Update extends Default {
}
分組使用
package com.example.share.entity;
import com.example.share.annotation.group.Create;
import com.example.share.annotation.group.Update;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.io.Serializable;
/**
* 自定義實體類
*/
@Data
public class UserEntityWithGroup implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 用戶主鍵
*/
@NotNull(message = "更新時惠爽,用戶主鍵不能為Null", groups = Update.class)
@Null(message = "創(chuàng)建時癌蓖,用戶主鍵必須為Null", groups = Create.class)
private Long id;
@NotNull(message = "創(chuàng)建的時候名稱不能為空", groups = Create.class)
private String name;
@Override
public String toString() {
return "UserEntityWithGroup{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
控制器中需要設(shè)置@Validated(groups屬性)的Groups屬性來決定需要啟用的校驗分組規(guī)則
package com.example.share.controller;
import com.example.share.annotation.group.Create;
import com.example.share.annotation.group.Update;
import com.example.share.entity.UserEntity;
import com.example.share.entity.UserEntityWithGroup;
import com.example.share.response.MyResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
/**
* 參數(shù)校驗測試控制器
*/
@RestController()
@RequestMapping("/paramVerification")
public class ParameterVerificationController {
/**
* 使用分組的方式校驗
* @param userEntityWithGroup
* @return
*/
@PostMapping("/user/group/update")
public MyResponse verifyUserEntityWithGroupUpdate(@RequestBody @Validated(Update.class) UserEntityWithGroup userEntityWithGroup){
System.out.println(userEntityWithGroup);
System.out.println("--------------校驗用戶實體類--------------");
return new MyResponse(0);
}
/**
* 使用分組的方式校驗
* @param userEntityWithGroup
* @return
*/
@PostMapping("/user/group/create")
public MyResponse verifyUserEntityWithGroupCreate(@RequestBody @Validated(Create.class) UserEntityWithGroup userEntityWithGroup){
System.out.println(userEntityWithGroup);
System.out.println("--------------校驗用戶實體類--------------");
return new MyResponse(0);
}
}