自定义注释不能验证方法参数

时间:2019-07-26 12:44:53

标签: java spring-boot validation annotations

我创建了一个自定义注释

@Documented
@Constraint(validatedBy = CheckGranularityValidator.class)
@Target( { ElementType.PARAMETER} )
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckGranularity {
    String message() default "Duration has to be a multiple of granularity";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

使用这样的验证器

public class CheckGranularityValidator implements ConstraintValidator<CheckGranularity, AssetCostsRequest> {

    @Override
    public void initialize(final CheckGranularity constraintAnnotation) {

    }

    @Override
    public boolean isValid(final AssetCostsRequest value, final ConstraintValidatorContext context) {
        return value.getRange().getDuration() % value.getGranularity() == 0;
    }
}

我尝试在RestController中使用它

@RestController
public class CalcApiController extends CalcApi {

@Override
public ResponseEntity<String> calcProfitability(@Valid @CheckGranularity @RequestBody final AssetCostsRequest assetCostsRequest) {
    return ResponseEntity.ok("Works");
}

我通过编写测试尝试使用此批注:

@Test
public void calcTest() {
    final AssetCostsRequest request = new AssetCostsRequest()
        .setRange(new TimeRange(100L, 200L))
        .setGranularity(26L);

    given()
        .contentType(ContentType.JSON)
        .body(request)
    .when()
        .post("/calc")
    .then()
        .statusCode(HttpStatus.SC_BAD_REQUEST);
}

AssetCostsRequest的相关部分:

public class AssetCostsRequest {

    @JsonProperty
    @NotNull
    private TimeRange range;

    @JsonProperty
    @NotNull
    private Long granularity = 30L;

    ...getters & setters
}

测试方法返回200。当我尝试在isValid方法中设置一个断点时,在运行测试时没有命中该断点。我尝试更改批注的顺序,摆脱@Valid,更改@Target类中的CheckGranularity,没有任何帮助。我正在使用RestAssured进行测试。

我该如何做,以便我的注释正确验证了一个参数?

1 个答案:

答案 0 :(得分:0)

ElementType.TYPE的目标更改为@CheckGranularity,并在AssetCostsRequest上直接添加$arr = [['contact_email' => 'a@a.com'], ['contact_email' => 'a@a.com'], ['contact_email' => 'b@a.com']]; $result = []; array_map(function ($item) use (&$result) { $result[$item['contact_email']] = $item; }, $arr); print_r($result);