我有一个条件,希望基于其他字段值有条件地应用一些验证。我已经为此创建了组约束,但是我不确定如何在自定义验证器类中使用这些约束组。我的约束组可以很好地用于诸如NOTNULL之类的预定义验证,但是我希望我的自定义验证器也仅在指定的组适用时才被调用。
我已经检查了api文档,但是找不到任何方法来获取当前适用的约束组。
static_assert( true == is_tpl_same<std::set, std::set>::value, "!" );
static_assert( false == is_tpl_same<std::vector, std::set>::value, "!" );
@RestController
@Slf4j
public class QuoteDetailController {
private QuoteDetailService applicationService;
@Autowired
public QuoteDetailController(QuoteDetailService applicationService) {
this.applicationService = applicationService;
}
@PostMapping(value = "/quote/retail")
public ResponseEntity<String> saveQuoteForRetail(
@RequestBody @Validated(value = RetailCustomerConstraintGroup.class) QuoteDetail quoteDetail) {
log.info("Request for saveQuote in controller : {}", quoteDetail);
String response = applicationService.saveQuote(quoteDetail);
log.info(response);
return ResponseEntity.ok(response);
}
@PostMapping(value = "/quote/corporate")
public ResponseEntity<String> saveQuoteForCorporate(
@RequestBody @Validated(value = CorporateCustomerConstraintGroup.class) QuoteDetail quoteDetail) {
log.info("Request for saveQuote in controller : {}", quoteDetail);
String response = applicationService.saveQuote(quoteDetail);
log.info(response);
return ResponseEntity.ok(response);
}
}
public class QuoteDetail {
private Long Id;
private Double price;
private String description;
private String customerType;
@ValidCustomer(groups= {RetailCustomerConstraintGroup.class,CorporateCustomerConstraintGroup.class})
private CustomerDetails customerDetails;
@NotNull(groups= CorporateCustomerConstraintGroup.class)
private ContactPersonDetail contactPersonDetail;
}
@Documented
@Constraint(validatedBy = {CustomerDetailValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCustomer {
public abstract String message() default "Invalid value.";
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default {};
public abstract boolean ignoreCase() default true;
}