我无法理解@ValidateOnExecution注释的本质.有人可以解释用例吗?
根据球衣的文档,资源方法的约束会自动验证.此代码段来自jersey’s example.
@GET
@NotNull
@HasId
public List<ContactCard> getContacts() {
return StorageService.findByName("");
}
@GET
@Path("{id}")
@NotNull(message = "{contact.does.not.exist}")
@HasId
public ContactCard getContact(
@DecimalMin(value = "0", message = "{contact.wrong.id}")
@PathParam("id") final Long id) {
return StorageService.get(id);
}
如果约束在pojo中,您可以使用@Valid(See)触发验证.
@Path("/")
class MyResourceClass {
@POST
@Consumes("application/xml")
public void registerUser(@Valid User user) {
...
}
}
那么@ValidateOnExecution用于什么除了明确关闭验证?
解决方法:
根据Jersey latest documentation @ValidateOnExecution,注释应该用于下一个目的:
According to Bean Validation specification, validation is enabled by default only for the so called constrained methods. Getter methods as defined by the Java Beans specification are not constrained methods, so they will not be validated by default. The special annotation @ValidateOnExecution can be used to selectively enable and disable validation. For example, you can enable validation on method getEmail shown in Example
@Path("/")
class MyResourceClass {
@Email
@ValidateOnExecution
public String getEmail() {
return email;
}
...
}
The default value for the type attribute of @ValidateOnExecution is IMPLICIT which results in method getEmail being validated.
因此@ValidateOnExecution也可以用于至少启用getter-methods的验证.