Here is a sample method:
@ApplicationScoped
public class MyClass{
public void getUser(@Min(1) int id){
//get User logic
}
}
I'm in a CDI environment with @ValidateOnExecution(type = ExecutableType.ALL)
by default, so I don't have to write any validation logic inside the method body. Here what happens if i call the method with an invalid value:
try{
getUser(-1);
} catch (ConstraintViolationException e) {
e.printStackTrace(); //this will be executed!
}
But this only happens if MyClass
is instantiated by CDI.
If someone manually instantiates MyClass
, of course its interceptors won't work. The reasons one may want to manually instantiate (using new
) a class could be the followings:
- Unit testing
- There is a public empty constructor, as for CDI requirements
So the question is: should I specify in my API contracts (that is, the javadocs) that getUser
throws ConstraintViolationException in case of bad input? As I explained above, this is not always true.
Is using bean validation interceptors a bad idea in this case?