2017-02-17 39 views
0

在我目前的項目中,我經常使用批量請求。我有簡單的BulkRequest<T>類:如何在REST服務中驗證泛型bean?

import java.util.List; 

import javax.validation.constraints.NotNull; 

public class BulkRequest<T> { 

    @NotNull private List<T> requests; 

    public List<T> getRequests() { return this.requests; } 

    public void setRequests(List<T> requests) { this.requests = requests; } 
} 

它非常簡單與其它bean中使用,例如:

@RequestMapping(value = "/departments/{departmentId}/patterns", 
       method = RequestMethod.POST, 
       produces = MediaType.APPLICATION_JSON_VALUE) 
public ResponseEntity<Object> post(
    final @PathVariable long departmentId, 
    final @Valid @RequestBody BulkRequest<AddPatternRequest> bulkRequest 
) { 
    ... 
} 

AddPatternRequest包含自己的規則進行驗證,並表示只有一個要求,它可以收集批量要求:

import javax.validation.constraints.NotNull; 

public class AddPatternRequest { 

    @NotNull private Long pattern; 

    public Long getPattern() { return this.pattern; } 

    public void setPattern(Long pattern) { this.pattern = pattern; } 
} 

但有一個問題。在控制器收到批量請求後,它僅驗證BulkRequest並檢查requests集合是否爲null,但是我也需要驗證嵌套請求。

我該怎麼辦?

回答

3

將@Valid添加到請求中。像這樣

@NotNull 
@Valid 
private List<T> requests; 

然後嵌套對象也驗證