Java --- springboot3web自定义yaml内容协商

目录

一、WebMvcConfigurationSupport

二、配置yaml内容协商格式


一、WebMvcConfigurationSupport

提供了很多的默认设置。
判断系统中是否有相应的类:如果有,就加入相应的HttpMessageConverter
 

jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
				ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);

二、配置yaml内容协商格式

导入pom依赖


        
            com.fasterxml.jackson.dataformat
            jackson-dataformat-yaml
        

修改springboot的配置文件

#增加yaml内容类型
spring.mvc.contentnegotiation.media-types.yaml=text/yaml

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

@Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer(){
            @Override //配置把对象转为yaml
            public void configureMessageConverters(List> converters) {
                converters.add(new YAMLHttpMessageConverter());
            }
        };
    }

编写自己的HttpMessageConverter

 */
public class YAMLHttpMessageConverter extends AbstractHttpMessageConverter {
    private ObjectMapper objectMapper = null;
    public YAMLHttpMessageConverter(){
        //告诉springboot支持的媒体类型
        super(new MediaType("text","yaml", Charset.forName("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;
    }

    @Override //@RequestBody
    protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

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

测试结果:

Java --- springboot3web自定义yaml内容协商_第1张图片

 

你可能感兴趣的:(springboot3,java,服务器,前端)