Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should be @ValidateOnExecution used with jersey?

I couldn't catch the essence of the @ValidateOnExecution annotation. Could someone please explain the use case for it?

According to jersey's documentation, constraints on resource methods are automatically validated. This code snippet is from 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);
}

If the constraints are in a pojo you can trigger validation with @Valid (See).

@Path("/")
class MyResourceClass {

@POST
@Consumes("application/xml")
public void registerUser(@Valid User user) {
    ...
}
}

So what is @ValidateOnExecution used for except explicitly turning off the validation?

like image 392
zolee Avatar asked Oct 31 '22 03:10

zolee


1 Answers

According to Jersey latest documentation @ValidateOnExecution annotation should be used for next purposes:

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.

Thus @ValidateOnExecution can be also used at least for enabling validation for getter-methods.

like image 185
dmaidaniuk Avatar answered Nov 04 '22 12:11

dmaidaniuk