53°

spring boot 自定义消息转换器

需求分析:在请求返回中,想统一返回的数据格式。在controller层中通过aop中的环绕通知实现了这个功能。但是在转换的过程中,提示没有自定义的格式转换器。所有我们需要自己实现这个转换器。

实现方式:通过继承 AbstractHttpMessageConverter这个类来实现功能。

public class ResultBeanConverter extends AbstractHttpMessageConverter<ResultBean> {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private static final String DEFAULT_SUBTYPE = "json";

    public ResultBeanConverter(){

        super(new MediaType("application", DEFAULT_SUBTYPE, DEFAULT_CHARSET));
    }

    @Override
    protected boolean supports(Class<?> aClass) {
        return ResultBean.class.isAssignableFrom(aClass);
    }

    @Override
    protected ResultBean readInternal(Class<? extends ResultBean> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return new ResultBean();
    }

    @Override
    protected void writeInternal(ResultBean resultBean, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

        StreamUtils.copy(resultBean.toString(), DEFAULT_CHARSET, httpOutputMessage.getBody());
    }
}

 

通过spring注入,解决问题。

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(resultBeanConverter());
        super.extendMessageConverters(converters);
    }

    @Bean
    public ResultBeanConverter resultBeanConverter(){

        return new ResultBeanConverter();
    }
}

 

本文由【一滴水穿石】发布于开源中国,原文链接:https://my.oschina.net/u/2319418/blog/2964118

全部评论: 0

    我有话说: