Search code examples
javabean-validationhibernate-validator

JSR 303. Validate method parameter and throw exception


How can I use JSR-303 validate method parameters and throw exception if parameter is not valid?

For example like this: public void createUser(@ValidOrThrowException User user) {...}?

For now, I check every method parameter in method body, like

public void createUser(User user) {
    ConstraintViolations violations = Validator.validate(user);
    if (!violations.isEmpty()) {
        throw new IllegalArgumentException(createExceptionMessage(violations ));
    }
    ...//business logic
}

and I think it's ugly.

P.S. As reference implementation I use Hibernate-validator 4.1.0.Final


Solution

  • If you can upgrade to Hibernate Validator 4.2.0 or above, you can use its method validation feature, which provides support for the validation of method parameters and return values.

    The validation engine can be invoked automatically upon the invocation of constrained methods using means such dynamic proxies, AOP, interceptors etc. Depending on the framework you work with, you can e.g. use one of the following:

    Note that as of Bean Validation 1.1 (to be finalized soon) and its reference implementation Hibernate Validator 5, method validation will be part of the standardized Bean Validation API.