Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Parameter Validation with JSR-303

Is JSR-303 also intended for method parameter validation?

If so, is there any example on the web? The biggest challenge I'm facing is how to get a validator within each method. With Spring 3, doesn't it mean that I'd have to inject virtually every class with a LocalValidatorFactoryBean?

Thanks!

like image 822
Tom Tucker Avatar asked Dec 12 '10 23:12

Tom Tucker


People also ask

What is JSR 303 Bean Validation?

Bean Validation. JSR-303 bean validation is an specification whose objective is to standardize the validation of Java beans through annotations. The objective of the JSR-303 standard is to use annotations directly in a Java bean class.

What does the @valid as part of JSR 303 mean?

The real use of @Valid annotation is in the class (bean) that you are validating with JSR 303 validator and its primary use is to validate the object graph. Meaning one bean can have other bean references with @Valid annotation to trigger validation recursively.

How do you validate a method in Java?

A backing bean method that performs validation must accept a FacesContext , the component whose data must be validated, and the data to be validated, just as the validate method of the Validator interface does. A component refers to the backing bean method by using its validator attribute.

In which implementation is the JSR 303 standard used?

Apache Bean Validation (formerly agimatec)


2 Answers

Method level validation will be supported in the upcoming version 4.2 of JSR 303's reference implementation Hibernate Validator.

As pointed out in the previous answer this will allow constraint annotations (built-in as well as custom defined types) to be specified at method parameters and return values to specify pre- and post-conditions for a method's invocation.

Note that HV will only deal with the actual validation of method calls not with triggering such a validation. Validation invocation could be done using AOP or other method interception facilities such as JDK's dynamic proxies.

The JIRA issue for this is HV-347 [1], so you might want to add yourself as watcher to this issue.

[1] http://opensource.atlassian.com/projects/hibernate/browse/HV-347

like image 110
Gunnar Avatar answered Sep 23 '22 04:09

Gunnar


The javadocs for each of the JSR 303 annotations tells the following:

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})

See, PARAMETER is there. So, yes, it's technically possible.

Here's an example:

public void method(@NotNull String parameter) {
    // ...
}

I'm however not sure how that integrates with Spring since I don't use it. You could just give it a try.

like image 32
BalusC Avatar answered Sep 26 '22 04:09

BalusC