SpringBoot内容协商(Content Negotiation)二 —— 自定义消息转换器(MessageConverter)

SpringBoot内置的消息转换器

SpringBoot没有处理返回yaml格式的数据,这里需要手动添加处理这种返回格式的支持。

导入依赖

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

添加配置

spring:
  mvc:
    contentnegotiation:     # 内容协商
      media-types:
        yaml: application/yaml  # 添加yaml格式返回支持

添加MessageConverter组件

public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private ObjectMapper objectMapper = null;

    public MyYamlHttpMessageConverter(){
        //告诉SpringBoot这个MessageConverter支持哪种媒体类型  //媒体类型
        super(new MediaType("application", "yaml", StandardCharsets.UTF_8));
        YAMLFactory factory = new YAMLFactory()
                .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
        this.objectMapper = new ObjectMapper(factory);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        //只要是对象类型,不是基本类型
        return true;
    }

    //@RequestBody 接受参数为yaml格式,不处理
    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    //@ResponseBody 把对象怎么写出去
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //try-with写法,自动关流
        try(OutputStream os = outputMessage.getBody()){
            this.objectMapper.writeValue(os,o);
        }
    }
}

增加HttpMessageConverter组件,专门负责把对象写出为yaml格式

@Configuration
public class MyConfig {

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(new MyYamlHttpMessageConverter());
            }
        };
    }
}

参考
[1] https://www.yuque.com/leifengyang/springboot3/wp5l9qbu1k64frz1#VHQfh
[2] https://springdoc.cn/spring-boot/web.html#web.servlet.spring-mvc.message-converters
[3] https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.servlet.spring-mvc.message-converters

posted @ 2023-10-25 14:37  雨中遐想  阅读(218)  评论(0)    收藏  举报