spring boot中rest控制器的post方法中的差异b/w@ResponseStatus和ResponseEntity.created(location).build()

spring boot中rest控制器的post方法中的差异b/w@ResponseStatus和ResponseEntity.created(location).build(),spring,spring-boot,model-view-controller,Spring,Spring Boot,Model View Controller,对于Rest控制器i wan中的post方法,返回201状态码。 我看到了两种方法。 第一个是 @PostMapping("/offers") @ResponseStatus(HttpStatus.CREATED) public Offer createOffer(@Valid @RequestBody Offer offer) { return offerRepository.Save(offer); } 第二种方法是 @PostMapping("/

对于Rest控制器i wan中的post方法,返回201状态码。 我看到了两种方法。 第一个是

@PostMapping("/offers")
     @ResponseStatus(HttpStatus.CREATED)
    public Offer createOffer(@Valid @RequestBody Offer offer) {
        return offerRepository.Save(offer);
    }
第二种方法是

@PostMapping("/offers")
    public ResponseEntity<Object> createOffer(@Valid @RequestBody Offer offer) {
        return offerService.createOffer(offer);
    }
@PostMapping(/offers)
public ResponseEntity createOffer(@Valid@RequestBody Offer Offer){
返回offerService.createOffer(offer);
}
下面是我的服务课
@覆盖
公共响应createOffer(要约){
报价uOffer=报价保存(报价);
URI位置=ServletUriComponentsBuilder.fromCurrentRequest().path(“/{jobTitle}”)。
buildAndExpand(uOffer.getJobTitle()).toUri();
返回ResponseEntity.created(location.build();
}

所以我的问题是,对于第一种方法,我们没有使用任何ResponseEntity.created,因为我们只是从控制器返回
@ResponseStatus(HttpStatus.created)
。但是在第二种方法中,我们没有使用
@ResponseStatus(HttpStatus.created)
,我们通过使用uri和ResponseEntity来处理状态代码201


这两种方法的区别是什么?它们似乎都返回相同的响应代码201。首选哪种方法?

第一种方法是首选方法,因为它允许您保持服务层与web层的解耦(服务层不应该知道
HttpEntity
以及所有这些内容,因此它可能在没有web层的情况下被重用)


您应该重构您的服务方法以返回
对象
,而不是
响应属性

对于状态代码,通常没有区别。最后,您仍然会得到一个状态代码为201的HTTP响应。 然而,在第二种方法中,您还返回一个
位置
头,这是一种首选方法。来自Mozilla的HTTP指南:

HTTP 201 Created success status响应代码表示请求已成功并导致资源的创建。在发送回此响应之前,将有效地创建新资源,并在消息体中返回新资源,其位置为请求的URL或位置标头的内容


我认为你应该遵守以下规则。如果要返回ResponseEntity,请使用它来影响状态。因此类似于:

@PostMapping("/offers")
public ResponseEntity<Offer> createOffer(@Valid @RequestBody Offer offer) {
     Offer offer = offerService.createOffer(offer);
     URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
                buildAndExpand(uOffer.getJobTitle()).toUri();
     return ResponseEntity.created(location)
                          .body(offer)
                          .build(); 
}
@PostMapping("/offers")
@ResponseStatus(HttpStatus.CREATED)
public Offer createOffer(@Valid @RequestBody Offer offer) {
     // Do not return response entity but the offer
     return offerService.createOffer(offer);
}

取决于你的使用情况。在某些情况下,不返回封装类的ResponseEntity,而是返回类本身。你必须使用@ResponseStatus来影响状态。我不会用处理ResponseEntity创建的代码来扰乱我的服务。我让它来处理你的控制器。两种方法都使用相同的服务类?他使用相同的服务,因此在第一个变体中没有解耦,但OP可以重构服务以返回
对象
,而不是
响应性
,并以简单的方式实现所需的解耦。