Spring HATEOAS(w Spring Boot)返回 Resources 或 PagedResources 结果时出现 JAXB 编组错误

2024-05-26

我的控制器中有这样的东西:

@RequestMapping
@ResponseBody
public HttpEntity<PagedResources<PromotionResource>> promotions(
        @PageableDefault(size = RestAPIConfig.DEFAULT_PAGE_SIZE, page = 0) Pageable pageable,
        PagedResourcesAssembler<Promotion> assembler
){

    PagedResources<PromotionResource> r = assembler.toResource(this.promoService.find(pageable), this.promoAssembler);

    return new ResponseEntity<PagedResources<PromotionResource>>(r, HttpStatus.OK);
}

如果我导航到映射到该控制器方法的 URL,我会收到 500 错误,其根本原因是:

com.sun.istack.internal.SAXException2: unable to marshal type "commerce.api.rest.resources.PromotionResource " as an element because it is missing an @XmlRootElement annotation 

如果我在资源上添加 @XmlRootElement 注释,则会出现以下错误:

com.sun.istack.internal.SAXException2: unable to marshal type "commerce.api.rest.resources.PromotionResource " as an element because it is not known to this context.

如果接受头是 application/json 或 application/hal+json ,一切都很好。仅当客户端(在本例中为 chrome)查找 application/xml 时才会出现此问题(这是有道理的,因为 HATEOAS 正在跟踪客户端请求。我正在使用 spring boot 的 @EnableAutoConfiguration 它将 XML 消息转换器添加到列表中从而启用 XML 内容类型。

我猜我至少有两个选择: 1.修复jaxb错误 2. 删除 xml 作为受支持的内容类型

不知道该怎么做,或者也许还有另一种选择。


如果您实际上不想生成 XML,请尝试使用produces的属性@RequestMapping注解。就像是:@RequestMapping(produces=MediaType.APPLICATION_JSON_VALUE)

或者你可以排除jaxb从您的类路径或查看添加您自己的org.springframework.boot.autoconfigure.web.HttpMessageConvertersbean 完全控制注册的HttpMessageConverter's. See WebMvcConfigurationSupport.addDefaultHttpMessageConverters查看 Spring 默认添加的内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring HATEOAS(w Spring Boot)返回 Resources 或 PagedResources 结果时出现 JAXB 编组错误 的相关文章

随机推荐