Nothing says you need to use @Valid in your controller methods only. Why not make a validation method that accepts a parameter you annotate as @Valid, then just return that same parameter.
Like this:
public Book validateBook(@Valid Book book) {
return book;
}
Looks like an alternative would be to use Hibernate's validation package. Here's it's documentation.
Basically, you get a Validator
from a ValidationFactory
, and then use the validator like this:
@Test
public void manufacturerIsNull() {
Car car = new Car(null, "DD-AB-123", 4);
Set<ConstraintViolation<Car>> constraintViolations =
validator.validate(car);
assertEquals(1, constraintViolations.size());
assertEquals("may not be null", constraintViolations.iterator().next().getMessage());
}