【问题标题】:Spring boot and Bean validation in different methods and the same class不同方法和同一个类中的 Spring Boot 和 Bean 验证
【发布时间】:2019-11-28 18:09:44
【问题描述】:

我正在使用 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。有可能做这样的事情吗?

【问题讨论】:

    标签: java spring spring-boot spring-mvc bean-validation


    【解决方案1】:

    我认为您应该在 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 接口以将它们用作您的验证组。

    【讨论】:

    • 我认为这个解决方案对于一些有很多方法的控制器来说不是很好,但对我来说它有效。谢谢你的回答。
    • 不客气,我认为在这种情况下,最好为不同的控制器方法定义不同类型的DTOs,而不是使用实际的实体。
    猜你喜欢
    • 1970-01-01
    • 2014-09-09
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多