首页 > 解决方案 > 无法推断 ResponseEntity<> 的类型参数

问题描述

我想实现 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);
  }

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

标签: javaspringspring-bootspring-mvc

解决方案


您可以使用

    ResponseEntity<Object> 

像那样

或者

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

  public class ResponseData {
      private Object payload;
   } 

并像那样使用 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);
   }

您也可以用 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);
   }

推荐阅读