首页 > 解决方案 > 在运行时使 @Valid 注释方法失败

问题描述

我有一个像这样的抽象类:

public abstract class Request implements RequestDto {

private final req ipwRequest = new IpwRequestMetadataDto();

    @Valid
    @Override
    public String getRequestId() {
        if (isRequestIdNull() && req.getRequestId() == null) {
            return null;
        }

        if (!isRequestIdNull() && req.getRequestId() != null && req.getRequestId().length() > 0) {
            return req.getRequestId();
        }

        String errorMessage = "Request id should " +
                (isRequestIdNull() ? "" : "not ") +
                "be null";
        throw new ConstraintViolationException(errorMessage, Collections.emptySet());
    }

    protected abstract boolean isRequestIdNull();
}

这个类可以被其他两个类覆盖,每个类都覆盖isRequestIdNull

我尝试通过使用这样的验证器来测试它是否正常工作:

@Test
public void testCreateRequest() {
    var dto = new CreateRequest();
    dto.setRequestId("11111");

    Set<ConstraintViolation<CreateRequest>> constraintViolations = validator.validate(dto);

    // Assert
    assertNotEquals(1, constraintViolations.size());
}

getRequestId 在调用验证器时被调用,但不是添加到constraintViolations,它只是抛出异常并崩溃。

如何添加到 constraintViolations 而不是抛出异常。

标签: javaspringspring-validator

解决方案


将 constraintViolations 作为参数传递给 getRequestId,并在函数 getRequestId 内有一个标志是抛出异常还是添加到 constraintViolations 列表中


推荐阅读