简体   繁体   中英

Bean Validation with groups using Spring in Service Layer

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?

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.

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

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

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM