@Validated没有考虑到

时间:2014-10-23 12:51:49

标签: java validation spring-mvc bean-validation

我有一个非常简单的REST服务设置,并开始使用Bean验证来验证它。一切都运行正常,直到我注意到我需要针对不同方法在同一对象上使用不同的Validations。

我尝试了群组验证。 我的问题是,当我用@Validated(Group.class)注释替换我的函数@Valid注释时,不再进行验证。

以下是我的对象和配置文件:

结束点:

 <jaxrs:server id="myRestServices" address="/v1">
    <jaxrs:serviceBeans>
        <ref bean="rentalsService"/>
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <ref bean="jsonProvider"/>
    </jaxrs:providers>
    <jaxrs:inInterceptors>
        <ref bean="validationInInterceptor" />
    </jaxrs:inInterceptors>
</jaxrs:server>
    <bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" />
<bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor">
     <property name="provider" ref="validationProvider" />
</bean>

服务:

public interface RentalsService {

public Rental createRental(@Validated({ CreateValidationGroup.class }) Rental rental);

public Rental updateRental(String RentalId, @Validated({ UpdateValidationGroup.class }) Rental rental);

ServiceImpl

@Path("/rentals")
@Produces(MediaType.APPLICATION_JSON)
public class RentalServiceImpl implements RentalsService {

private RentalBusinessService rentalBusinessService;

@POST
@Override
@Consumes(MediaType.APPLICATION_JSON)
public Rental createRental(@Validated({ CreateValidationGroup.class }) Rental rental) {
    return rentalBusinessService.createRental(rental);
}

@PUT
@Override
@Path("/{RentalId}")
@Consumes(MediaType.APPLICATION_JSON)
public Rental updateRental(@PathParam("RentalId") String RentalId, @Validated({ UpdateValidationGroup.class }) Rental rental) {
    return rentalBusinessService.updateRental(RentalId, rental);
}

` 所说的群体:

    public interface CreateValidationGroup {

}  public interface UpdateValidationGroup {

}

最后是对象:

public class Rental {   

@Size(min = 2, max = 14, groups = { UpdateValidationGroup.class }, message = " 2 < Status < 4 ") 
private String status;


@NotNull
@Size(min = 2, max = 14, message = " 2 < Product < 4 ")
private String product;

@Size(min = 2, max = 14, groups = { CreateValidationGroup.class }, message = " 2 < ID < 4 ")
private String RentalId;

我不能这样使用群组验证吗?将@Validated切换回@Valid会触发验证。

1 个答案:

答案 0 :(得分:0)

所以我继续前进并且手动完成:

注入一个Smartvalidator,并在指定该组时调用我的对象上的validate方法。这是我试图避免的......

private SmartValidator validator;

private RentalBusinessService rentalBusinessService;

@POST
@Override
@Consumes(MediaType.APPLICATION_JSON)
public Rental createRental(Rental rental) {

    Errors errors = new BeanPropertyBindingResult(rental, "rental");
    validator.validate(rental, errors, CreateValidationGroup.class);

    if (errors.hasErrors()) {
       //dostuff
    }

注入的bean:

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

如果有人知道如何通过注释做到这一点,我仍然想知道我哪里出错了。