如何使用@Valid验证局部变量?

时间:2015-06-25 15:59:24

标签: java hibernate validation hibernate-validator

这是问题here的后续内容。如何将@Valid添加到局部变量?

以下是来自班级AuthorizationServer的代码:

@NotBlank
private String authorizationServerId;

@Property
@Indexed(unique = true)
@NotBlank
private String authorizationUrl;

@Property(policy = PojomaticPolicy.TO_STRING)
@NotBlank
private String clientAuthorizationUrl;

@NotBlank
private String deviceRootCert;

这是控制器:

byte[] bytes = IOUtils.toByteArray(request.getInputStream());
        String signature = authorization.split(":")[1];

        ObjectMapper mapper = objectMapper();
        AuthorizationServer authorizationServer = mapper.readValue(bytes, 
        AuthorizationServer.class);

如何针对authorizationServer类中声明的注释验证AuthorizationServer

当我尝试

@Valid
AuthorizationServer authorizationServer = mapper.readValue(bytes, AuthorizationServer.class);

我收到错误@Valid not applicable to local variable

2 个答案:

答案 0 :(得分:0)

我认为这个例外说明了一切。 Bean Validation不允许验证局部变量。它是关于通过属性验证验证类状态或者您可以进行方法验证。没有局部变量验证这样的东西。

答案 1 :(得分:0)

是的, Bean验证不允许验证局部变量。但是,您可以执行以下操作:

@javax.validation.executable.ValidateOnExecution    
AuthorizationServer getAuthorizationServer(ObjectMapper mapper){
    return mapper.readValue(bytes, AuthorizationServer.class);
}