DiveInto
DiveInto

Reputation: 2266

Bean validation only works for controller methods in Spring?

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

Answers (1)

Rafal G.
Rafal G.

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:

  1. You could extract this logic to another, package protected scoped, Spring component, inject it to the controller and call it instead of your localValidate method,
  2. Inject org.springframework.validation.Validator to your controller and call it manually

Upvotes: 1

Related Questions