使用Spring Data Rest的控制器和存储库的相同URL映射
问题描述:
我使用Spring Data Rest作为自动休息端点和HATEOAS。当我去为localhost:8080,我得到:使用Spring Data Rest的控制器和存储库的相同URL映射
{
"_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 @本地:8080 /书籍给我: 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链接。