Skip to content

SpringBoot 基于 valid 自定义金额校验注解

spring-boot-starter-validation 里面已经自带了很多常见的参数校验的注解,但对某一些特定的参数没有相关的注解, 比如说金额, 本文介绍如何自定义一个参数校验注解

添加 maven 依赖

java
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

自定义校验注解类

java
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MaxMoneyConstraintValidator.class)
public @interface MaxMoney {

    String message() default "max money error";

    double value() default 0;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

自定义校验类

java
public class MaxMoneyConstraintValidator implements ConstraintValidator<MaxMoney, BigDecimal> {

    private MaxMoney constraint;

    @Override
    public void initialize(MaxMoney constraintAnnotation) {
        this.constraint = constraintAnnotation;
    }

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext constraintValidatorContext) {
        return value != null && value.doubleValue() < constraint.value();
    }
}

使用自定义校验注解

java
public class MaxMoneyDemo {

    @MaxMoney(value = 10,message = "价格不能大于10")
    private BigDecimal price;

    public MaxMoneyDemo() {
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}

编写测试 controller

java
@RestController
public class TestController {


    @PostMapping("/test")
    public String test(@Valid @RequestBody MaxMoneyDemo moneyDemo) {
        return "success";
    }
}

发送请求

text
curl --location --request POST 'http://127.0.0.1:8080/test' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
    "price":10
}'
text
Validation failed for argument [0] in public java.lang.String com.example.valid.controller.TestController.test(com.example.valid.model.MaxMoneyDemo): [Field error in object 'maxMoneyDemo' on field 'price': rejected value [10]; codes [MaxMoney.maxMoneyDemo.price,MaxMoney.price,MaxMoney.java.math.BigDecimal,MaxMoney]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [maxMoneyDemo.price,price]; arguments []; default message [price],10.0]; default message [价格不能大于10]] ]

可以看到我们自定义的注解已经生效

Released under the MIT License.