I have the following API method:
@GetMapping
public ResponseEntity<List<Project>> getProjects(@RequestParam(required = false) String userName, @RequestParam(required = false) boolean additionalInfo) {
return ResponseEntity.ok(projectService.getProjects(userName, additionalInfo));
}
当前返回 ResponseEntity<List<Project>>
。但如果可选参数 additionalInfo
是真的,我想返回 ResponseEntity<List<ProjectAdditionalInfoDTO>>
。我如何定义返回类型以表明它们都可以返回?当然我可以使用ResponseEntity<?>
,但那会很难看。
最佳答案
我会让事情变得简单,只是将事情分成两个单独的 Controller 方法......例如
@GetMapping
public ResponseEntity<List<Project>> getProjects(@RequestParam(required=false) String userName) {
//...
}
@GetMapping
public ResponseEntity<List<ProjectAdditionalInfoDTO>> getProjectsWithAdditionalInfos(@RequestParam(required=false) String userName, @RequestParam(required=true) boolean additionalInfo) {
//...
}
关于java - API方法可以返回不同的类型,我如何定义返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59305587/