0
votes

I am developing a service(not a web application) using Spring-3.1.0.GA. I want to use hibernate-validator along with Spring to validate my service inputs.

I have enabled the bean validation support with:

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

I have annotated my service interface with @Validated and method parameters with @NotNull, @Size, @Valid etc and it is working fine.

But I have to validate my parameter, say Customer, based on validation group(s). If I annotate method parameter with @Validated or @Validated(Group1.class) Spring is not performing any validation.

If I annotate with @Valid then validations are happening but with Default validation group(as expected).

I can't annotate @Validate(Group1.class) at interface level because various methods operate on various groups.

How can I perform service layer validations using Spring and hibernate-validator with groups support?

3
Do you need to enable annotations? E.g. something the lines of adding <mvc:annotation-driven/> to applicationContext.xml (although that would be for a Spring MVC application, which yours does not seem to be). - vegemite4me

3 Answers

1
votes

I have gone through Spring Source code and why the validation groups on method params are not being picked...As per the code it is picking the validation groups configuration only from @Validated on interface level, not on method level.

But I haven't gone through how it is working in SpringMVC context, I haven't checked yet.

Also in this process I came to know If you configure MethodValidationPostProcessor in child application context it is not picked up by Spring. I mean if you are using SpringMVC, MethodValidationPostProcessor will be registered only if you configure it in [servlet-name]-servlet.xml. If you configure in any child context configuration files that are picked by ContextLoaderListener Spring won't register MethodValidationPostProcessor. Also I am not sure it is only for MethodValidationPostProcessor or for any BeanPostProcessors also.

1
votes

I get the following code working, I need to attach the @Validated at the method header and @Valid in the method parameters.

@Validated(Default.class)
public UserDto updateUser(@Valid UserDto userDto) {
0
votes

In Spring 3.1.0+ you can use groups directly in @Valid annotation. E.g.:

@Valid(groups={Default.class, Group1.class})