简体   繁体   中英

How to validate generic bean in REST service?

In my current project I frequently use bulk requests. I have simple BulkRequest<T> class:

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; }
}

It very simple to use with other beans, for example:

@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 contains own rules for validation and represents only one request, which can be collected to bulk request:

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; }
}

But there's a problem. After the controller receives the bulk request, it validates only BulkRequest and checks if requests collection is null or not, but I need to validate nested request too.

How can I do it?

Add @Valid to the requests. Like this

@NotNull 
@Valid
private List<T> requests;

Then nested objects are also validated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM