在SpringBoot中配置自定义HttpMessageConverter

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

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

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

  1. package com.example.testrest;
  2. import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
  3. import org.springframework.context.annotation.*;
  4. import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
  5. import org.springframework.oxm.xstream.XStreamMarshaller;
  6. @Configuration
  7. public class MyConfiguration {
  8. @Bean
  9. public HttpMessageConverters customConverters() {
  10. MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
  11. XStreamMarshaller xstream = new XStreamMarshaller();
  12. xmlConverter.setMarshaller(xstream);
  13. xmlConverter.setUnmarshaller(xstream);
  14. return new HttpMessageConverters(xmlConverter);
  15. }
  16. }

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

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

  1. public class Customer {
  2. private int id;
  3. private String name;
  4. public Customer(int id, String name) {
  5. super();
  6. this.id = id;
  7. this.name = name;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. }

这是控制器类:

  1. @RestController
  2. public class CustomerController {
  3. @Autowired CustomerRepository repository;
  4. @RequestMapping(value = "/list", method = RequestMethod.GET)
  5. public List<Customer> findAll() {
  6. return repository.getData();
  7. }
  8. @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
  9. public Customer findOne(@PathVariable int id) {
  10. return repository.getData().get(id);
  11. }
  12. }

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

  1. curl --header "Accept: application/xml" http://localhost:8080/list
  2. <list>
  3. <com.example.testrest.Customer>
  4. <id>1</id>
  5. <name>frank</name>
  6. </com.example.testrest.Customer>
  7. <com.example.testrest.Customer>
  8. <id>2</id>
  9. <name>john</name>
  10. </com.example.testrest.Customer>
  11. </list>

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

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

相关文章