JSR 303. Validate method parameter and throw exception

我的梦境 提交于 2019-12-01 11:58:57

问题


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


回答1:


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:

  • When working with Spring 3.1 or later: MethodValidationInterceptor
  • When working with CDI: Seam Validation (disclaimer: I'm the author of this)
  • When working with Guice: I've added an example for this on GitHub

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.



来源:https://stackoverflow.com/questions/14829487/jsr-303-validate-method-parameter-and-throw-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!