在SpringBoot中配置自定义HttpMessageConverter

x33g5p2x  于2022-10-05 转载在 Spring  
字(2.2k)|赞(0)|评价(0)|浏览(1198)

HttpMessageConverter 提供了一种在 Web 应用程序中添加和合并其他转换器的便捷方式。 在本教程中,我们将学习如何指定一个额外的 HttpMessageConverter 并将其添加到默认配置中。

这是一个示例类,它提供了额外的 HtpMessageConverterMarshallingHttpMessageConverter

package com.example.testrest;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;

@Configuration
public class MyConfiguration {
  @Bean
  public HttpMessageConverters customConverters() {
    MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
    XStreamMarshaller xstream = new XStreamMarshaller();
    xmlConverter.setMarshaller(xstream);
    xmlConverter.setUnmarshaller(xstream);
    return new HttpMessageConverters(xmlConverter);
  }
}

MarshallingHttpMessageConverter 使用 XStreamMarshaller 作为编组器/解组器。 XStreamMarshaller 能够在不添加注释的情况下将任何 Java 类转换为 XML。

在我们的例子中,我们将使用它来编组/解组以下 Java Bean 类:

public class Customer {
  private int id;
  private String name;

  public Customer(int id, String name) {
    super();
    this.id = id;
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

这是控制器类:

@RestController
public class CustomerController {
  @Autowired CustomerRepository repository;

  @RequestMapping(value = "/list", method = RequestMethod.GET)
  public List<Customer> findAll() {
    return repository.getData();
  }

  @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
  public Customer findOne(@PathVariable int id) {
    return repository.getData().get(id);
  }
}

您可以看到编组器的效果。 请求客户列表时:

curl --header "Accept: application/xml" http://localhost:8080/list  
<list>
	<com.example.testrest.Customer>
		<id>1</id>
		<name>frank</name>
	</com.example.testrest.Customer>
	<com.example.testrest.Customer>
		<id>2</id>
		<name>john</name>
	</com.example.testrest.Customer>
</list>

另一方面,您仍然可以将客户列表请求为 JSON:

curl --header "Accept: application/json" http://localhost:8080/list [{"id":1,"name":"frank"},{"id":2,"name":"john"}]

本教程的源代码:https://github.com/fmarchioni/masterspringboot/tree/master/mvc/custom-converter

相关文章

微信公众号

最新文章

更多