?还有一种自定义注解是通过AOP和注解实现的,本文暂不介绍。
一、pom
<!-- 用于注解校验 -->
<!--jsr 303-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- hibernate validator-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
二、自定义注解
2.1、注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Constraint(validatedBy = BankNoValidator.class)
public @interface BankNo {
String message() default "银行账号错误";
/**
* 将validator进行分类,不同的类group中会执行不同的validator操作
*
* @return validator的分类类型
*/
Class<?>[] groups() default {};
/**
* 主要是针对bean,很少使用
*
* @return 负载
*/
Class<? extends Payload>[] payload() default {};
}
2.2、配置校验类
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class BankNoValidator implements ConstraintValidator<BankNo, String> {
@Override
public void initialize(BankNo constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
@Override
public boolean isValid(String bankNo, ConstraintValidatorContext constraintValidatorContext) {
return null !=bankNo && !"".equals(bankNo);
}
}
三、测试
3.1、全局异常处理器
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @ClassName: GlobalExceptionHandler
* @Description: 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(MethodArgumentNotValidException.class)
public CommonResponseDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("{}", e.getBindingResult().getFieldError().getDefaultMessage());
return CommonResponseDTO.builder().code("1002")
.message(e.getBindingResult().getFieldError().getDefaultMessage()).build();
}
}
3.2、请求类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("fund_user")
@ApiModel(value="User对象", description="用户表")
public class FundUser implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "银行账号")
@BankNo
private String bankNo;
}
@Data
@Builder
public class CommonResponseDTO<T> {
private String code;
private String message;
private T data;
}
3.3、测试类
@RestController
public class TestApi {
@PostMapping("/testPost")
public void testPost(@Valid @RequestBody FundUser user){
System.out.println(user.toString());
}
}
3.4、postman测试
测试成功!
|