JSR303验证不适用于spring4.0



我正在使用spring(4.2.0.RELEASE)、hibernate验证器(5.2.1.Final)和验证api(1.1.0.Final)进行JSR验证,用于以下配置的后端应用程序

<bean id="validatorFactory" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource" />
</bean>
<bean class="org.springframework.expression.spel.standard.SpelExpressionParser" />

但是JSR303注释在我的应用程序中都不起作用。

注意:在POJO类上添加了jsr 303注释,在服务类(使用POJO)上添加了@Validated注释,还尝试在方法级别上添加@Validated。

更新:服务接口

@Validated 
public interface SampleService {
@NotNull
@Valid
Account getAccount( @NotNull @Valid String customerKey, @NotNull String name);

服务实施

@Service
@Validated
@Transactional( readOnly=true )
public class SampleServiceImpl
    implements SampleService
{
    private final SampleDao sampleDao;
@Inject
public SampleServiceImpl( SampleDao sampleDao)
{
    this.sampleDao= sampleDao;
}

@Override
@Validated
public Customer getAccount( String customerKey, String name)
{
    try {
        return sampleDao.getAccount( customerKey, name);
    }
    catch ( EmptyResultDataAccessException e ) {
        throw new NotFoundException( e );
    }
}

有以下几点:

1-您需要验证POJO,因此创建一个POJO并用您想要的验证对其进行注释,即:

public class Customer {
    @NotNull
    private String name;
    @NotNull
    private String customerKey;
    ...
}

2-@Valid注释需要在实现上:

@Override
public Customer getAccount(@Valid Customer customer, BindingResult bindingResult) {}

3-确保Spring xml上有<mvc:annotation-driven/>

BindingResult在方法上不是必需的,但它会为您提供找到的验证错误,并允许您在发回响应之前对它们进行处理。

重复的问题,请阅读这篇

服务层验证

此链接解释了默认情况下,仅在控制器层中支持弹簧注释验证。对于服务层,要么重用一些spring组件并调整一些配置,要么推出自己的AOP。但我建议选择前者。重复使用。

相关内容

最新更新