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" />

但没有一个 JSR 303 注释在我的应用程序中工作。

注意:在 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 );
    }
}
4

2 回答 2

0

重复的问题,请阅读此问题

服务层验证

此链接说明默认情况下,仅在控制器层中支持 spring 注释验证。对于服务层,你要么重用一些 spring 组件并调整一些配置,要么滚动你自己的 AOP。但我建议只选择前者。重用。

于 2016-04-13T13:10:02.327 回答
0

有几件事:

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-确保你有<mvc:annotation-driven/>你的Spring xml。

您的方法不需要 BindingResult,但它会为您提供发现的验证错误,并允许您在发回响应之前对其进行处理。

于 2016-04-13T08:39:40.170 回答