基于操作的javax验证

Ram*_*dam 0 java validation spring

我正在尝试在DTO上使用javax验证。但是我希望根据此DTO的操作来应用这些验证。

可以说我有以下DTO:

@Getter @Setter
public class CustomerDTO {

    @NotNull
    private String id;

    @NotNull 
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用相同的DTO进行创建,更新和删除操作。在进行更新和删除操作的情况下,我希望“ id”为NotNull,但在Create中必须为null。

但是由于我使用相同的DTO,并且在控制器级别使用@Valid注释,因此它适用于所有属性。并且以下API失败,因为“ id”不能为null

public CustomerDTO createCustomer(@Valid CustomerDTO customer, BindingResults results){
    if(results.hasErrors()){
        throw IllegalArgumentsException("Required params are mising");
    }
    customerService.create(customer);
}
Run Code Online (Sandbox Code Playgroud)

kag*_*ole 5

由于您使用的是Spring,因此可以使用其@Validated注释和系统。

运作方式:每个验证注解都有一个field groups。此字段使您可以基于类确定何时进行验证。您可以执行以下操作:

  1. ValidationGroups用所需的所有验证组创建一个类。例:
import javax.validation.groups.Default;

/**
 * Utility classes to distinct CRUD validations.<br>
 * <br>
 * Used with the
 * {@link org.springframework.validation.annotation.Validated @Validated}
 * Spring annotation.
 */
public final class ValidationGroups {

    private ValidationGroups() {
    }

    // Standard groups

    public interface Create extends Default {};
    public interface Replace extends Default {};
    public interface Update extends Default {};
    public interface Delete extends Default {};
}
Run Code Online (Sandbox Code Playgroud)
  1. 对于您的情况,请id按以下方式注释字段:
@Null(
    groups = Create.class
)
@NotNull(
    groups = { Update.class, Delete.class }
)
private String id;
Run Code Online (Sandbox Code Playgroud)
  1. 最后,告诉控制器端您要使用@Validated注释而不是@Valid一个组来验证哪个组:
public CustomerDTO createCustomer(@Validated(Create.class) CustomerDTO customer, BindingResult results) {
    if(results.hasErrors()){
        throw IllegalArgumentsException("Required params are mising");
    }
    customerService.create(customer);
}

// Etc. You can put multiple groups like @Validated({ Update.class, Delete.class })
Run Code Online (Sandbox Code Playgroud)

关于extends javax.validation.groups.Defaultin的注意事项ValidationGroups

如果您不使用扩展您的Createjavax.validation.groups.Default,那么如果您使用@Validated不带参数的注释,则验证规则将不会完成。

// @Validated without argument validate every annotation with the "Default" group
public void test(@Validated MyForm form, BindingResult results) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

您可以继承验证。例如,如果您要Replace验证所有Create验证规则,请设置ReplaceInherit Create

public interface Create extends Default {};
public interface Replace extends Create {};
Run Code Online (Sandbox Code Playgroud)