java使用Spring引导验证通用Rest Api
通过引用这个reference,我已经为基本CRUD操作实现了通用RESTAPI服务
这非常有效,但现在我还希望在进一步处理之前验证我的请求
下面是我的通用Rest控制器定义
public abstract class GenericRestResource<DTO extends BaseDTO> {
protected final ICrudService<DTO> facade;
protected GenericRestResource(ICrudService<DTO> facade) {
this.facade = facade;
}
@GetMapping
public List<DTO> list() {
return facade.findAll();
}
@GetMapping(value = "/{id}")
public DTO get(@PathVariable(value = "id") Long id) throws NotFoundException {
return facade.find(id).orElseThrow(() -> new NotFoundException(String.format("could not get item with id: %s", id)));
}
@PostMapping
public Long create(@RequestBody @Valid DTO dto) {
return facade.create(dto);
}
@PutMapping(value = "/{id}")
public void update(@PathVariable("id") Long id, @RequestBody DTO dto) {
facade.edit(id, dto);
}
@DeleteMapping(value = "/{id}")
public void delete(@PathVariable(value = "id") Long id) {
facade.delete(id);
}
}
食物资源。爪哇
@RestController
@RequestMapping(path = "/api/v1/foo")
@Validated
public class FooResource extends GenericRestResource<FooDTO> {
@Autowired
protected FooResource (ICrudService<FooDTO> facade) {
super(facade);
}
}
BaseDTO。爪哇
@NoArgsConstructor
@AllArgsConstructor
@Data
public abstract class BaseDTO {
protected Long id;
}
食物。爪哇
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
public class FooDTO extends BaseDTO {
@NotNull(message = "id is mandatory", groups = {OnUpdate.class, Delete.class})
@JsonProperty("categoryId")
private Long categoryID;
@NotBlank(message = "identifier is mandatory", groups = {OnCreate.class, OnUpdate.class})
private String identifier;
@NotBlank(message = "identifier is mandatory", groups = {OnCreate.class, OnUpdate.class})
private String placeholder;
}
但是,这不会验证对FooDTO的请求,FooDTO是BaseDTO的一种类型。验证仅适用于BaseDTO如果我在id上添加任何验证查询,如@NotNull,我还希望验证FooDTO。 当前的执行有什么问题?请帮助我理解这一点,我如何才能让它工作
共 (0) 个答案