java spring引导示例hateoas不工作
我正在尝试运行位于https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-hateoas的hateoas spring引导示例(我正在尝试运行版本1.2.6.RELEASE)
当访问示例提供的客户服务时,我得到一个异常:
Could not marshal [Resources { content: [sample.domain.Customer@72c01d5a, sample.domain.Customer@5ef1ebf9, sample.domain.Customer@237de11a], links: [http://localhost:8080/customers;rel="self"] }]: null; nested exception is javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: class sample.domain.Customer nor any of its super class is known to this context. javax.xml.bind.JAXBException: class sample.domain.Customer nor any of its super class is known to this context.]
这是由以下代码引起的:
@RequestMapping(method = RequestMethod.GET)
HttpEntity<Resources<Customer>> showCustomers() {
Resources<Customer> resources = new Resources<Customer>(this.repository.findAll());
resources.add(this.entityLinks.linkToCollectionResource(Customer.class));
return new ResponseEntity<Resources<Customer>>(resources, HttpStatus.OK);
}
虽然我可以实现我自己的
public class CustomerResources extends Resources<Customer> {
如果可能的话,我想避免这种情况
如果必须是这样的话,我很困惑为什么在这个例子中不是这样的。我错过什么了吗?我怎样才能使样品起作用
提前谢谢
# 1 楼答案
使用HATEOAS时,异常:javax。xml。绑定如果未使用URI添加正确的生产者类型,则会发生MarshalException
无论何时在Spring boot中使用HATEOAS,都需要添加类型为application/hal+json
例如: @PostMapping(value=“/yourUri”,生成=“应用程序/hal+json”)
这对我有用
# 2 楼答案
该示例旨在使用JSON,并在默认情况下提供JSON。我猜您正在发送一个带有
Accept
头的请求,该头请求application/xml
。请尝试删除标头,或改为请求application/json