1、引入maven依赖(版本太低也会导致不生效)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.7.10</version>
</dependency>
2、创建注解接口(javax.validation版本是2.0.0的,自行选择,太低也不行)
package com.wang.test.annotation;
import com.wang.test.annotation.CheckField.List;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
//主要标记在什么代码上可以使用
// TYPE,//类,接口(包括注解类型)或枚举的声明
// FIELD,//属性的声明
// METHOD,//方法的声明
// PARAMETER,//方法形式参数声明
// CONSTRUCTOR,//构造方法的声明
// LOCAL_VARIABLE,//局部变量声明
// ANNOTATION_TYPE,//注解类型声明
// PACKAGE//包的声明
@Target({METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER,TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(List.class)
//CheckValidator 自定义类,主要用于注解校验
@Constraint(validatedBy = CheckValidator.class)
public @interface CheckField {
String message() default "密码必须包含至少一个大写字母、一个小写字母和一个数字";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER,TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
CheckField[] value();
}
}
package com.wang.test.annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
//CheckField 自定义注解的接口
public class CheckValidator implements ConstraintValidator<CheckField, String> {
private static final String PASSWORD_PATTERN = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";
@Override
public void initialize(CheckField constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// if (!value.matches(PASSWORD_PATTERN)) {
// throw new RuntimeException("大大");
// }
// return value.matches(PASSWORD_PATTERN);
if (value.contains("*")){
throw new RuntimeException("包含");
}else {
return true;
}
}
}
3、可以创建全局异常来捕获(Result可以自己定义)
package com.wang.test.annotation;
import com.wang.test.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.SystemException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SystemException.class)
public Result systemExceptionHandler(SystemException e) {
log.error("出现了异常! {}", e);
return Result.nok(e.getCause().getMessage());
}
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e) {
log.error("出现了异常! {}", e);
return Result.nok(e.getCause().getMessage());
}
/* 添加校验参数异常处理 */
@ExceptionHandler(BindException.class)
public Result bindExceptionHandler(BindException e) {
log.error("出现了异常! {}", e);
return Result.nok(e.getCause().getMessage());
}
}
4、统一返回结果类文章来源:https://www.toymoban.com/news/detail-656220.html
package com.wang.test.utils;
public class Result<T> {
private static final String SUCCESS = "SUCCESS";
private static final String FAIL = "FAIL";
private String code;
private String message;
private T Data;
public Result(String code) {
this.code = code;
}
public Result(String code, String message) {
super();
this.code = code;
this.message = message;
}
public Result(String code, String message, T data) {
super();
this.code = code;
this.message = message;
Data = data;
}
public Result() {
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return Data;
}
public void setData(T data) {
Data = data;
}
public static <T> Result<T> ok(T object) {
return new Result<T>(SUCCESS, "", object);
}
public static <T> Result<T> ok() {
return new Result<T>(SUCCESS);
}
public static <T> Result<T> nok(String message) {
return new Result<T>(FAIL, message);
}
public static <T> Result<T> nok() {
return new Result<T>(FAIL);
}
public static <T> Result<T> nok(String code, String message) {
return new Result<T>(code, message);
}
public static <T> Result<T> nok(String code, String message, T object) {
return new Result<T>(code, message, object);
}
}
5、场景使用文章来源地址https://www.toymoban.com/news/detail-656220.html
package com.wang.test.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.wang.test.annotation.CheckField;
import com.wang.test.utils.CustomStringStringConverter;
import lombok.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
//@Accessors(chain = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WaterMeter implements Serializable {
/**
@CheckField(message = "dadad")
@TableField("waterMeter")
@ExcelProperty(value = {"水表数据","水表名"},converter = CustomStringStringConverter.class)
private String waterMeter;
private List<@Valid uesr> uesrList;
}
package com.wang.test.entity;
import com.wang.test.annotation.CheckField;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @BelongsPackage: com.wang.test.entity
* @Author: wangqian
* @CreateTime: 2023-08-08 09:15:59
* @Describe:
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class uesr {
String id;
@CheckField()
String age;
}
//这个是接口,需要在接口传参上加@Validated 注解,
//注解版本(org.springframework:spring-context:5.3.26)
@PostMapping("/getDataById")
public Result a(@Validated @RequestBody WaterMeter waterMeter){
// WaterMeter waterMeter = waterMeterService.getDataById(id);
return Result.ok(waterMeter);
}
到了这里,关于springboot 自定义注解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!