2017-05-30 40 views
0

我正在設計一個用於創建新員工的REST API。Spring驗證+ Swagger文檔:基於其他領域的條件或值

根據員工類型,將會有必填字段,否則它們不是。例如:所有創建API調用都應該通過employeeName。但contractVendorName應該是強制性的只有employeeType=contractor

問題:

  1. 如何使用Spring的驗證執行這樣的限制?
  2. 如何在Swagger中記錄這些字段?
  3. 如果不支持有條件的驗證,是否有意義有不同的API,用於
    • createEmpoyee(ContractEmployee CE)
    • createEmpoyee(RegularEmployee重)
      在ContractEmployee對象做彈簧+招搖的註釋標記contractVendorName爲必填項。

這裏,我已經採取了只有一個領域爲例,contractVendorName。我可能有5-6個字段,根據Employee類型可選或強制。我寧願使用spring驗證,這樣我就不必編寫樣板代碼來自己檢查所有的驗證。多個員工類型對象的副作用是API的增加。由於每個對象類型都需要一個單獨的API。

的方法什麼好的建議有單獨的對象+多個API與自API,並與各界一個對象,並以此爲基礎進行的員工類型爲每個字段手動驗證?

public class EmployeeDTO { 

     /** 
     * Employee Type: full-time, part-time, permanent, contractor 
     */ 
     @NotNull 
     @ApiModelProperty(required = true) 
     private String employeeType; 

     /** 
     * Mandatory field that is to be given by client 
     */ 
     @NotBlank 
     @ApiModelProperty(required = true) 
     private String employeeName; 


     /** 
     * How to make this field mandatory when employeeType = contractor ? 
     * Is this possible in Spring? 
     * How to document it in Swagger? 
     */ 
     private String contractVendorName; 

} 

回答

0

您需要類級約束才能實現此目的。閱讀​​

@Target({ TYPE, ANNOTATION_TYPE }) 
@Retention(RUNTIME) 
@Constraint(validatedBy = { VendorNameCheckValidator.class }) 
@Documented 
public @interface VendorNameCheck { 

    String message() default "{some.message}"; 

    Class<?>[] groups() default { }; 

    Class<? extends Payload>[] payload() default { }; 
} 



public class VendorNameCheckValidator 
     implements ConstraintValidator<ValidPassengerCount, EmployeeDTO> { 

    @Override 
    public void initialize(VendorNameCheck constraintAnnotation) { 
    } 

    @Override 
    public boolean isValid(EmployeeDTO dto, ConstraintValidatorContext context) { 
     if (dto == null) { 
      return true; 
     } 

     return !"contractor".equals(dto.getEmployeeType()) || isNotEmpty(dto.getContractVendorName()); 
    } 
}