restTemplate.getforobject(),exchange(),entity()。每种方法都有优缺点吗?

ben*_*nny 11 spring resttemplate

我已经使用了entity(),exchange(),getforObject(),并且一切似乎都正常。但不确定哪种方法适用于不同的情况。.请提供有关每种方法的更多信息,例如利弊,在何处使用,何处不使用。

amd*_*mdg 8

您实际上可以阅读RestTemplate 的文档以了解这些方法的目的。没有优缺点。每种方法都有自己的目的。

getforObject() :发送HTTP GET请求,返回从响应主体映射的对象。

 @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public @ResponseBody Employee employeeById(@PathVariable long id) {
       return employeeRepository.findEmp(id);
    }
Run Code Online (Sandbox Code Playgroud)

如果存储库找不到给定ID的任何员工,则将null发送带有status 的响应200(OK)。但是实际上,有问题。找不到数据。200(OK)应该发送而不是发送404(Not Found)。因此,一种方式是发送ResponseEntity(携带更多与响应相关的元数据(标头/状态码)。)

@RequestMapping(value="/{id}", method=RequestMethod.GET)
 public ResponseEntity<Employee> employeeById(@PathVariable long id) {
   Employee employee = employeeRepository.findEmp(id);
   HttpStatus status = HttpStatus.NOT_FOUND;
   if(employee != null ){
     status = HttpStatus.OK; 
   }       
   return new ResponseEntity<Employee>(employee, status);
}
Run Code Online (Sandbox Code Playgroud)

在这里,客户将知道其请求的确切状态。

exchange:针对URL执行指定的HTTP方法,返回,其中 ResponseEntity包含从响应主体映射的对象

  • 因此,基本上的区别在于,getForEntity() 比 getForObject() 提供更多元数据。使用 getForObject() 比 getForEntity() 有什么优势吗? (2认同)