Reputation: 2266
Tried with code below, seems in Spring, bean validation only works for controller methods(those who annotated with @RequestMapping), plain methods won't trigger bean validation.
@RequestMapping(value = "/test-validate", method = RequestMethod.POST)
public String test(@Validated Obj obj){
return "validation-works";
}
@RequestMapping(value = "/test-local-method-validate", method = RequestMethod.POST)
public String test2(@Validated Obj obj){
Obj obj = new Obj();
localValidate(obj);//won't validate, though content is null
}
void localValidate(@Validated Obj obj){
log.debug("entered");
}
//Model
public class Obj{
@NotNull
public String content = null;
}
if we call the first method: /test-validate, the validation would trigger, while for the second method: /test-local-method-validate, we call with a local plain method: localValidate, the validation doesn't work.
If it's true, how can I enable bean validation in plain methods?
Upvotes: 2
Views: 1945
Reputation: 4432
The answer is: it will not work in your current code because when calling localValidate(obj)
you are skipping the Spring created proxy completely and this proxy is responsible for the validation part.
Options:
localValidate
method,org.springframework.validation.Validator
to your controller and call it manuallyUpvotes: 1