Enterprise Java

Method parameter validation with Spring and JSR 303

Spring provides an easy way to validate method parameters using JSR 303 bean validation. In this post we will see how to use this feature.

Setup

First we need to add support for method parameter validation by creating a MethodValidationPostProcessor bean:

1
2
3
4
5
6
7
@Configuration
public class MyConfiguration {
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
}

Validating method parameters

After registering the MethodValidationPostProcessor we can enable method parameter validation per bean by adding the @Validated annotation. Now we can add Java Bean validation annotations to our method parameter to perform validation.

1
2
3
4
5
6
7
8
@Service
@Validated
public class UserService {
 
    public User getUser(@NotBlank String uuid) {
        ...
    }
}

Here we added a @NotBlank annotation to make sure the passed uuid parameter is not null or an empty string. Whenever an invalid uuid is passed a ContraintViolationException will be thrown.

Besides simple parameter validation we can also validate objects annotated with JSR 303 annotations.

For example:

1
2
3
4
5
6
7
public class User {
 
    @NotBlank
    private String name;
 
    // getter + setter
}
1
2
3
4
5
6
7
8
@Service
@Validated
public class UserService {
 
    public void createUser(@Valid User user) {
        ...
    }
}

By adding @Valid (not @Validated) we mark the user parameter for validation. The passed user object will then be validated based on the validation constraints defined in the User class. Here the name field should not be null or contain an empty string.

How does this work?

The MethodValidationPostProcessor bean we registered is a BeanPostProcessor that checks each bean if it is annotated with @Validated. If thats the case it will add an AOP interceptor (MethodValidationInterceptor) to intercept method calls and performs validation. The actual bean method is only called if the validation was successful.

Because this feature relies on AOP interceptors it works only on spring beans.

As always you can find the sources for the shown examples on GitHub.

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: Method parameter validation with Spring and JSR 303

Opinions expressed by Java Code Geeks contributors are their own.

Michael Scharhag

Michael Scharhag is a Java Developer, Blogger and technology enthusiast. Particularly interested in Java related technologies including Java EE, Spring, Groovy and Grails.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button