![](/img/trans.png)
[英]How to mix Spring Data Repositories and Spring Rest Controllers
[英]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/books
和POST @ localhost:8080/books
普通控制器方法?
為了實現自定義端點嘗試使用@RepositoryRestController
,而是如果@RestController
如Spring Data REST
使用來自不同流Spring Web
和@RestController
注釋可能根本沒有工作和沖突Spring Data REST
。
您還可以添加@ExposesResourceFor
注釋以支持HATEOAS鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.