Search code examples
javaspringspring-bootspring-mvcbean-validation

Spring boot and Bean validation in different methods and the same class


I'm doing a rest webservice with spring boot and I would like to know if is possible do different validations with bean validation annotations by method with a POJO as param in the controller layer.

example:

POJO:

    Public class Person{
            @NotNull(forMethod="methodOne")
            private String firstName;
            @NotNull(forMehotd="methodTwo")
            private String lastName;
            private String age;

            //getter and setter
    }

Controller

    @RestController
    public class controller{

        @RequestMapping(....)
        public ResponseEntity methodOne(@Valid @RequestBody Person person){
            .....
        }

        @RequestMapping(....)
            public ResponseEntity methodTwo(@Valid @RequestBody Person person){
            ......
        }
    }

I know that is possible do it with separate parameters in the methods, but I have a POJO with so many attributes. is it possible do something like that?


Solution

  • I think you should use validation groups in your bean validation annotations and use @Validated annotation instead of @Valid annotation. because @Validated annotation has a value properties that specifies a group for validation.

    for example:

    Public class Person{
            @NotNull(groups={MethodOne.class})
            private String firstName;
            @NotNull(groups={MethodTwo.class})
            private String lastName;
            private String age;
    
            //getter and setter
    }
    

    and

    @RestController
    public class controller{
    
        @RequestMapping(....)
        public ResponseEntity methodOne(@Validated(MethodOne.class) @RequestBody Person person){
            .....
        }
    
        @RequestMapping(....)
            public ResponseEntity methodTwo(@Validated(MethodTwo.class) @RequestBody Person person){
            ......
        }
    }
    

    by the way, don't forget that you should create MethodOne and MethodTwo interfaces to use them as your validation groups.