簡體   English   中英

使用Spring Data Rest為控制器和存儲庫創建相同的url映射

[英]Same url mapping for controllers and repositories using Spring Data Rest

我正在使用Spring Data Rest來實現自動休息端點和HATEOAS。 當我去localhost:8080我得到:

   {
  "_links": {
    "books": {
      "href": "http://localhost:8080/books{?page,size,sort}",
      "templated": true
    },
    "users": {
      "href": "http://localhost:8080/users"
    },
    "customers": {
      "href": "http://localhost:8080/customers"
    },
    "profile": {
      "href": "http://localhost:8080/profile"
    }
  }
}

GET @ localhost:8080 / books給了我: There was an unexpected error (type=Method Not Allowed, status=405). Request method 'GET' not supported There was an unexpected error (type=Method Not Allowed, status=405). Request method 'GET' not supported

這是我的回購:

    public interface BookRepository extends PagingAndSortingRepository<Book, Long> {
  Optional<Book> findByIsbn(String isbn);
}

我的控制器:

   @RestController
public class BookController {
  private final BookService bookService;

  @Autowired
  public BookController(BookService bookService) {
    this.bookService = bookService;
  }

  @PostMapping("/books")
  @ResponseStatus(HttpStatus.CREATED)
  public Book newToDo(@RequestBody BookDTO bookDTO) {
    return bookService.addNewBook(bookDTO);
  }

  @PutMapping("/books/{id}")
  public ResponseEntity<?> editToDo(@PathVariable("id") Long id, @RequestBody double newPrice) {
    return new ResponseEntity<>(bookService.changePrice(id, newPrice), HttpStatus.OK);
  }
}

如果沒有那個控制器, GET @ localhost:8080/books可以完美地運行 - 存儲庫本身設置了這個端點,我可以搜索我的所有書籍。 當我添加POST和PUT方法時,我收到了一個錯誤。 有沒有辦法使用存儲庫進行GET requests @ localhost:8080/booksPOST @ localhost:8080/books普通控制器方法?

為了實現自定義端點嘗試使用@RepositoryRestController ,而是如果@RestControllerSpring Data REST使用來自不同流Spring Web@RestController注釋可能根本沒有工作和沖突Spring Data REST

您還可以添加@ExposesResourceFor注釋以支持HATEOAS鏈接。

暫無
暫無

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

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