【问题标题】:Same url mapping for controllers and repositories using Spring Data Rest使用 Spring Data Rest 的控制器和存储库的相同 url 映射
【发布时间】:2017-03-06 23:52:59
【问题描述】:

我将 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 的普通控制器方法?

【问题讨论】:

    标签: java spring spring-mvc spring-data-rest


    【解决方案1】:

    对于自定义端点的实现,尝试使用@RepositoryRestController,而不是如果@RestController as Spring Data REST 使用与Spring Web@RestController 不同的流程,注释可能根本不起作用并且与Spring Data REST 冲突。

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

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 2020-05-07
      • 2011-09-20
      • 1970-01-01
      • 2015-06-23
      相关资源
      最近更新 更多