Spring boot 在Spring Boot中返回不同类型响应的最佳方法是什么
我想为spring boot rest API返回两个不同的响应 当我收到sonar问题时,我不应该使用通配符。“通用通配符类型不应该在返回类型中使用” 我的代码:Spring boot 在Spring Boot中返回不同类型响应的最佳方法是什么,spring-boot,restapi,Spring Boot,Restapi,我想为spring boot rest API返回两个不同的响应 当我收到sonar问题时,我不应该使用通配符。“通用通配符类型不应该在返回类型中使用” 我的代码: @GetMapping(path = {"/v1/{type}"}, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> method(@PathVariable(value = "type&qu
@GetMapping(path = {"/v1/{type}"}, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> method(@PathVariable(value = "type") boolean type) {
boolean b = type;// some logic
if (b) {
Success result=new Success();
result.setSuccess("Yes");
return new ResponseEntity<>(result,HttpStatus.OK);
}
else {
Error result=new Error();
result.setError("No");
return new ResponseEntity<>(result,HttpStatus.CONFLICT); //appropriate error code
}
}
不声称是“最佳方式”,但一种方法可以是:
package com.my.package;
public interface MyResponseI { //if Error, Success (and others) have more "in common", you can also introduce an (abstract) class (with fields, methods, etc.)!
}
@...
public ResponseEntity<com.my.package.MyResponseI> ...
@。。。
公共责任。。。
有用的链接/条目:
- ,而且
- 及
@GetMapping("/testresponse/{id}")
public ResponseEntity<?> testMyResponse(@PathVariable("id") int id)
{
if(id==1)
return ResponseEntity.ok(new Success());
else return new ResponseEntity<>(new Error(), HttpStatus.CONFLICT);
}
public class Success {
private String msg = "Success";
public String getMsg() {
return msg;
}
}
public class Error {
private String msg = "Error";
public String getMsg() {
return msg;
}
}
嗨&欢迎来到!对于两个(-不是太多)响应对象(假设您可以更改它们),您可以使用“继承”/定义这两个对象的接口/超类!?我认为堆栈溢出是由于:
返回新的…
,“try”代替:返回这个代码>!;)Howie S.Nguyen:请查看上面的代码。当我使用上述方法时,我得到了java stackoverflow异常。事实证明,至少对我来说非常简单。我刚刚更新了上面的帖子Howie S.Nguyen:我不应该使用通配符,因为我收到sonar问题“通用通配符类型不应该用于返回类型”@bkumon,你上面显示的代码发生了这种情况,不是吗?请查看上面的代码。当我使用上述方法时,我得到了java stackoverflow异常
package com.my.package;
public interface MyResponseI { //if Error, Success (and others) have more "in common", you can also introduce an (abstract) class (with fields, methods, etc.)!
}
public class Success implements com.my.package.MyResponseI { //everything else can stay}
public class Error implements com.my.package.MyResponseI { //everything else can stay}
@...
public ResponseEntity<com.my.package.MyResponseI> ...
@GetMapping("/testresponse/{id}")
public ResponseEntity<?> testMyResponse(@PathVariable("id") int id)
{
if(id==1)
return ResponseEntity.ok(new Success());
else return new ResponseEntity<>(new Error(), HttpStatus.CONFLICT);
}
public class Success {
private String msg = "Success";
public String getMsg() {
return msg;
}
}
public class Error {
private String msg = "Error";
public String getMsg() {
return msg;
}
}
public ResponseEntity<MyResponse> method(@PathVariable(value = "type") boolean type)
return new ResponseEntity<>(result, HttpStatus.OK);
//for status 200 OK
return ResponseEntity.ok(result);