繁体   English   中英

Spring Boot 和 Bean 验证在不同方法和同一个类中

[英]Spring boot and Bean validation in different methods and the same class

我正在使用 spring boot 做一个 rest webservice,我想知道是否可以通过在控制器层中使用 POJO 作为参数的方法对 bean 验证注释进行不同的验证。

例子:

POJO:

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

            //getter and setter
    }

控制器

    @RestController
    public class controller{

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

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

我知道可以在方法中使用单独的参数来做到这一点,但是我有一个具有如此多属性的 POJO。 有可能做这样的事情吗?

我认为您应该在 bean 验证注释中使用validation groups并使用@Validated注释而不是@Valid注释。 因为@Validated注释有一个value属性,它指定了一个用于验证的组。

例如:

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

        //getter and setter
}

@RestController
public class controller{

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

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

顺便说一下,不要忘记您应该创建MethodOneMethodTwo接口以将它们用作验证组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM