0

In Springboot project, when I try to add @Validated on controller method, it worked.But now I want to add it on a common method, then failed.

Try to add @Validated on controller method, it worked

public class TaskValidator {
    private static final Logger logger = LogManager.getLogger("TaskValidatorLogger");
    public void validateTest(@Validated Test test) {
        logger.info("Validate: {}", test.getName());
    }

    public static void main(String[] args) {
        new TaskValidator().validateTest(new Test());
    }
}
@Data
public class Test {
    @NotNull(message = "name can not be null")
    private String name;
}

It should throw an MethodArgumentNotValidException but not.

何子洋
  • 47
  • 6

1 Answers1

0

Spring MVC has the ability to automatically validate @Controller inputs. In previous versions it was up to the developer to manually invoke validation logic.

In the controller methods, springboot automatically binds any validators to the model and invoke it when the data is bound to the object.

But in your case , you are trying to validate an object in which case , springboot might not be automatically binding your validator to your model and call the validator.So, in that case, you will need to manually bind the object to the validator.

or you can manually invoke the validator on a bean like :

@AutoWired
Validator validator;
...

validator.validate(book);
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39