When use ResponseEntity and @RestController for Spring RESTful applications

后端 未结 4 1322
Happy的楠姐
Happy的楠姐 2020-11-27 09:12

I am working with Spring Framework 4.0.7, together with MVC and Rest

I can work in peace with:

  • @Controller
  • ResponseEntity&
4条回答
  •  无人及你
    2020-11-27 09:40

    According to official documentation: Creating REST Controllers with the @RestController annotation

    @RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

    It seems that it's best to use @RestController for clarity, but you can also combine it with ResponseEntity for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

    For example:

    @RestController
    public class MyController {
    
        @GetMapping(path = "/test")
        @ResponseStatus(HttpStatus.OK)
        public User test() {
            User user = new User();
            user.setName("Name 1");
    
            return user;
        }
    
    }
    

    is the same as:

    @RestController
    public class MyController {
    
        @GetMapping(path = "/test")
        public ResponseEntity test() {
            User user = new User();
            user.setName("Name 1");
    
            HttpHeaders responseHeaders = new HttpHeaders();
            // ...
            return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
        }
    
    }
    

    This way, you can define ResponseEntity only when needed.

    Update

    You can use this:

        return ResponseEntity.ok().headers(responseHeaders).body(user);
    

提交回复
热议问题