基于spring的组动态POJO验证 [英] Dynamic POJO validation based on groups in spring

查看:167
本文介绍了基于spring的组动态POJO验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下pojo作为参考:

Consider the following pojo for reference:

public class User{

    private  String username;
    private String firstName;
    private String middleName;
    private String lastName;
    private String phone;

    //getters and setters

}

我的应用程序基本上是基于spring-boot的REST API,它暴露了两个端点,一个用于创建用户,另一个用于检索用户。

My application is a basically spring-boot based REST API which exposes two endpoints, one to create the user and the other to retrieve a user.

用户下降进入某些类别, group-a group-b 等,这是我从帖子请求的标题中获得的。

The "users" fall into certain categories, group-a, group-b etc. which I get from the headers of the post request.

我需要在运行时验证用户数据,验证可能会因用户组而有所不同。

I need to validated the user data in runtime and the validations may differ based on the group of a user.

例如,属于组的用户 - a可能有电话号码作为可选字段,而它可能是其他组的必填字段。

for example, the users that fall into group-a may have phone numbers as an optional field whereas it might be a mandatory field for some other group.

正则表达式也可能因其组而异。

The regex may also vary based on their groups.

我需要能够配置spring,以某种方式动态验证我的pojo,并根据他们的组触发它们各自的验证集。

I need to be able to configure spring, to somehow dynamically validate my pojo as soon as they are created and their respective set of validations get triggered based on their groups.

也许我可以创建一个yml / xml c onfiguration,这将允许我启用这个?

Maybe I can create a yml/xml configuration which would allow me to enable this?

我宁愿不用<$注释我的私人字符串电话 c $ c> @NotNull 和 @Pattern

I would prefer to not annotate my private String phone with @NotNull and @Pattern.

我的配置如下:

public class NotNullValidator implements Validator {
    private String group;
    private Object target;

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public void validate(Object o) {
        if (Objects.nonNull(o)) {
            throw new RuntimeException("Target is null");
        }
    }
}


public interface Validator {
    void validate(Object o);
}


@ConfigurationProperties(prefix = "not-null")
@Component
public class NotNullValidators {
    List<NotNullValidator> validators;

    public List<NotNullValidator> getValidators() {
        return validators;
    }

    public void setValidators(List<NotNullValidator> validators) {
        this.validators = validators;
    }
}



application.yml < br>


application.yml

not-null:
  validators:

    -
      group: group-a
      target: user.username

    -
      group: group-b
      target: user.phone

我想配置我的应用程序以某种方式允许验证器选择他们的目标(实际的对象,>提到的字符串在yml)中,并在其目标上调用各自的 public void validate(Object o)

I want to configure my application to somehow allow the validators to pick their targets (the actual objects, not the strings mentioned in the yml), and invoke their respective public void validate(Object o) on their targets.

PS

请随时编辑问题以使其更好。

Please feel free to edit the question to make it better.

我是使用jackson序列化和反序列化JSON。

I am using jackson for serializing and deserializing JSON.

推荐答案

对于你的问题最简单的解决方案,就像我看到的那样,不是Spring或POJO本身,但有一个设计模式。

The easiest solution to your problem, as i see it, is not with Spring or the POJOs themselves but with a design pattern.

你所描述的问题是easil y通过策略模式解决方案解决。

The problem you're describing is easily solved by a strategy pattern solution.

您可以匹配请求中所期望的标头使用的策略,描述用户的类型,然后您在策略本身内执行所述验证。

You match the strategy to use by the header you're expecting in the request, that describes the type of user, and then you perform said validations inside the strategy itself.

这将允许您对整个方法使用相同的POJO,并根据处理/解析和验证数据的细节处理对于每种类型的用户策略。

This will allow you to use the same POJO for the whole approach, and deal with the specifics of handling/parsing and validating data according to the each type of user's strategy.

这是来自维基书籍的链接,其中包含对模式的详细解释

Here's a link from wiki books with a detailed explanation of the pattern

策略模式

假设您有一个基本的策略接口:

Suppose you have a basic interface for your strategies:

interface Strategy { 

    boolean validate(User user);
}

对于2种不同类型的用户,您有2种不同的实现:

And you have 2 different implementations for the 2 different types of user:

public class StrategyA implements Strategy {

    public boolean validate(User user){

         return user.getUsername().isEmpty();
    }
}

public class StrategyB implements Strategy {

    public boolean validate(User user){

         return user.getPhone().isEmpty();
    }
}

您为<$ c $添加策略属性c>用户 POJO,并在收到邮件请求时为该属性分配正确的策略实现。

You add a Strategy attribute to your User POJO and assign the right implementation of the Strategy to that attribute when you receive the post request.

每当您需要验证该用户的数据时,您只需调用指定策略的 validate 方法。

Everytime you need to validate data for that user you just have to invoke the validate method of the assigned strategy.

如果每个用户可以适合多种策略,您可以添加列表<策略> 一个属性而不是一个属性。

If each User can fit multiple strategies, you can add a List<Strategy> as an attribute instead of a single one.

如果您不想更改POJO,则每次收到一个帖子请求时都必须检查哪个是正确的策略。

If you don't want to change the POJO you have to check which is the correct strategy every time you receive a post request.

除了验证方法外,您还可以添加处理数据的方法,特定于每种策略。

Besides the validate method you can add methods to handle data, specific to each strategy.

希望这有帮助。

这篇关于基于spring的组动态POJO验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆