本文介绍了Spring引导,如何使用@Valid与List< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将验证放到Spring Boot项目中。所以我将 @NotNull 注释添加到实体字段。在控制器中,我这样检查:

I am trying to put validation to a Spring Boot project. So I put @NotNull annotation to Entity fields. In controller I check it like this:

@RequestMapping(value="", method = RequestMethod.POST)
public DataResponse add(@RequestBody @Valid Status status, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        return new DataResponse(false, bindingResult.toString());
    }

    statusService.add(status);

    return  new DataResponse(true, "");
}

这是有效的。但当我使用输入 List< Status>状态,它不起作用。

This works. But when I make it with input List<Status> statuses, it doesn't work.

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid List<Status> statuses, BindingResult bindingResult) {
    // some code here
}

基本上,我想要的是将add方法中的验证检查应用于请求体列表中的每个Status对象。所以,发件人现在会有哪些对象有错,哪些没有。

Basically, what I want is to apply validation check like in the add method to each Status object in the requestbody list. So, the sender will now which objects have fault and which has not.

我怎样才能以简单快捷的方式做到这一点?

How can I do this in a simple, fast way?

推荐答案

我的直接建议是将List包装在另一个POJO bean中。并将其用作请求正文参数。

My immediate suggestion is to wrap the List in another POJO bean. And use that as the request body parameter.

在您的示例中。

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid StatusList statusList, BindingResult bindingResult) {
// some code here
}

和StatusList.java将

and StatusList.java will be

@Valid
private List<Status> statuses;
//Getter //Setter //Constructors

我没试过。

更新:
接受的答案给出了一个很好的解释,说明为什么列表不支持bean验证。

Update:The accepted answer in this SO link gives a good explanation why bean validation are not supported on Lists.

这篇关于Spring引导,如何使用@Valid与List&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:24