使用Spring Data Rest为控制器和存储库创建相同的url映射

时间:2017-03-06 23:52:59

标签: java spring spring-mvc 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

这是我的回购:

    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的常规控制器方法?

1 个答案:

答案 0 :(得分:0)

对于自定义端点的实现,尝试使用@RepositoryRestController代替@RestController Spring Data REST使用来自Spring Web的不同流,而@RestController注释可能根本不起作用和冲突Spring Data REST

您还可以添加@ExposesResourceFor注释以支持HATEOAS链接。