簡體   English   中英

覆蓋標准的Spring Data REST API

[英]Override standart Spring Data REST API

我的應用中有一個實體User Spring Data REST為我提供了標准端點:

`GET`    /user
`GET`    /user/<id>
`POST`   /user
`PUT`    /user
`PATCH`  /user
`DELETE` /user/<id>

我需要覆蓋DELETE端點的默認行為,而不是更改端點url /user 如果我向控制器添加以下內容:

@Controller
@RequestMapping("/user")
public class User {

    @DeleteMapping("/{id}")
    @CrossOrigin
    public ResponseEntity<?> delete(@PathVariable("id") final String id) {
        userService.delete(id); // in service I remove user with other 
        return ResponseEntity.ok().build();
    }

    // other custom endpoints

}

我發現其他標准REST端點不起作用 - 我總是收到405錯誤。 所以,我的問題是 - 如何自定義此端點而不影響其他端點? (我知道如何在@RepositoryEventHandler執行此操作 - 但在我的情況下我應該避免這種情況)

你讀過這個: 覆蓋Spring Data REST響應處理程序嗎?

@RepositoryRestController
@RequestMapping("/users") // or 'user'? - check this...
public class UserController {

    @Autoware 
    private UserRepo userRepo;

    @Transactional 
    @DeleteMapping("/{id}") 
    public ResponseEntity<?> delete(@PathVariable("id") String id) { // or Long id?..

        // custom logic

        return ResponseEntity.noContent().build();
    }
}

但是,如果要添加額外的業務邏輯來刪除進程,您甚至不需要實現自定義控制器,您可以使用自定義事件處理程序

@Component
@RepositoryEventHandler(User.class) 
public class UserEventHandler {

  @Autoware 
  private UserRepo userRepo;

  @BeforeDeleteEvent
  public void beforeDelete(User u) {
    //...
    if (/* smth. wrong */) throw new MyException(...);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM