5

コントローラーに次のようなものがあります。

@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.

Accept ヘッダーが application/json または application/hal+json であれば問題ありません。この問題は、クライアント (この場合はクロム) が application/xml を探している場合にのみ発生します (HATEOAS がクライアントの要求に従っているため、これは理にかなっています。XML メッセージ コンバーターをリストに追加するスプリング ブートの @EnableAutoConfiguration を使用しています)。したがって、XML コンテンツ タイプを有効にします。

少なくとも 2 つのオプションがあると思います: 1. jaxb エラーを修正する 2. サポートされているコンテンツ タイプから xml を削除する

どちらかを行う方法がわからないか、別のオプションがあるかもしれません。

4

3 に答える 3

1

これが良いテクニックかどうかはわかりません.1.1.6には別のアプローチがあるようです. これが私がしたことです:

@Configuration
public class WebMVCConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Remove the Jaxb2 that is automatically added because some other dependency brings it into the classpath
        List<HttpMessageConverter<?>> baseConverters = new ArrayList<HttpMessageConverter<?>>();
        super.configureMessageConverters(baseConverters);

        for(HttpMessageConverter<?> c : baseConverters){
            if(!(c instanceof Jaxb2RootElementHttpMessageConverter)){
                converters.add(c);
            }
        }
    }

}
于 2014-09-02T16:34:40.553 に答える