[英]JSR 303 validations are not working for spring 4.0
我正在使用spring(4.2.0.RELEASE),休眠验证器(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" />
但JSR 303注释在我的应用程序中均不起作用。
注意:在POJO类上添加了jsr 303注释,在服务类上添加了@Validated(正在使用POJO),也尝试在方法级别添加@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批注验证。 对于服务层,您只需要重用一些spring组件并调整一些配置,或者滚动您自己的AOP。 但是我建议选择前者。 重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.