想要在RequestBody Pojo类上提供自定义注释

时间:2019-06-13 12:38:48

标签: spring spring-boot

我们可以提供@valid批注,但我想在@RequestBody处提供自定义批注。

用例:在我的Pojo类中,我有两个字段firstname和lastname。所以我想以这种方式验证pojo类,如果用户为任何字段提供了值(例如为姓氏指定的值),那就很好了。但是Both字段都不能为空。用户应至少提供一个字段的值(是或条件)

我的Pojo课堂:

class Person {
     private String firstName;
     private String lastName;
 }

我们不能为两个字段都提供@NotNull。所以我想在课程级别上提供自定义注释。

在该验证器中,我将检查两个字段并将正确的错误消息发送给用户。

1 个答案:

答案 0 :(得分:0)

您可以尝试Custom ConstraintValidator,简单示例@ValidatePerson

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@RestController
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @PostMapping
    public Person doSomeThingPerson(@Validated @RequestBody Person person) {
        return person;
    }

    @ValidatePerson
    public static class Person {
        private String firstName;
        private String lastName;

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }
    }

    @Target({TYPE})
    @Retention(RUNTIME)
    @Constraint(validatedBy = {PersonValidator.class}) // you can use multiply validators
    public @interface ValidatePerson {

        String message() default "Invalid Person, firstName and lastName can't be null";

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

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

    }

    public static class PersonValidator implements ConstraintValidator<ValidatePerson, Person> {

        @Override
        public boolean isValid(Person person, ConstraintValidatorContext context) {
            return person.getFirstName() != null || person.getLastName() != null;
        }
    }

}

如果firstNamelastName均为null,则:

{
    "timestamp": 1560456328285,
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "ValidatePerson.person",
                "ValidatePerson"
            ],
            "arguments": [
                {
                    "codes": [
                        "person.",
                        ""
                    ],
                    "arguments": null,
                    "defaultMessage": "",
                    "code": ""
                }
            ],
            "defaultMessage": "Invalid Person, firstName and lastName can't be null",
            "objectName": "person",
            "code": "ValidatePerson"
        }
    ],
    "message": "Validation failed for object='person'. Error count: 1",
    "path": "/"
}

您还可以使用@ControllerAdvice

自定义例外