无法推断 ResponseEntity<> 的类型参数

Pet*_*zov 4 java spring spring-mvc spring-boot

我想实现 Spring 端点,我可以在其中返回 XML 对象NotificationEchoResponse和 http 状态代码。我试过这个:

@PostMapping(value = "/v1/notification", produces = "application/xml")
  public ResponseEntity<?> handleNotifications(@RequestParam MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature)) 
     {
         return new ResponseEntity<>("Please contact technical support!", HttpStatus.INTERNAL_SERVER_ERROR);
     }         

    return new ResponseEntity<>(new NotificationEchoResponse(unique_id), HttpStatus.OK);
  }
Run Code Online (Sandbox Code Playgroud)

但我收到错误:Cannot infer type arguments for ResponseEntity<>在这一行:return new ResponseEntity<>("Please contact technical support!", HttpStatus.INTERNAL_SERVER_ERROR);你知道我如何解决这个问题吗?

Ash*_*ari 6

您可以使用

    ResponseEntity<Object> 
Run Code Online (Sandbox Code Playgroud)

像那样

或者

您可以创建自己的自定义类,例如 ResponseData,并在该类中放置一个字段,例如 paylod

  public class ResponseData {
      private Object payload;
   } 
Run Code Online (Sandbox Code Playgroud)

并像那个 ResponseEntity 一样使用并设置该值。

现在你的控制器看起来像这样

    @PostMapping(value = "/v1/notification", produces = "application/xml")
    public ResponseEntity<ResponseData> handleNotifications(@RequestParam 
    MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature)) 
   {
     return new ResponseEntity<ResponseData>(new ResponseData("Please contact to technical support"), 
    HttpStatus.INTERNAL_SERVER_ERROR);
   }         

   return new ResponseEntity<ResponseData>(new ResponseData(new NotificationEchoResponse(unique_id)), 
   HttpStatus.OK);
   }
Run Code Online (Sandbox Code Playgroud)

您也可以用 Object 替换响应数据,然后

  @PostMapping(value = "/v1/notification", produces = "application/xml")
    public ResponseEntity<Object> handleNotifications(@RequestParam 
    MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature)) 
   {
     return new ResponseEntity<Object>("Please contact to technical support", 
    HttpStatus.INTERNAL_SERVER_ERROR);
   }         

   return new ResponseEntity<Object>(new NotificationEchoResponse(unique_id), 
   HttpStatus.OK);
   }
Run Code Online (Sandbox Code Playgroud)