开发者

聊聊springboot中如何自定义消息转换器

目录
  • 核心接口
  • springboot默认提供的转换器
  • 如何自定义消息转换器

Spring Boot 中的消息转换器(HttpMessageConverter)是处理 HTTP 请求和响应数据格式转换的核心组件,负责将 HTTP 请求体中的数据转换为 Java 对象,或将 Java 对象转换为 HTTP 响应体的数据。

核心接口

public interface HttpMessageConverter<T> {
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
    List<MediaType> getSupportedMediaTypes();
    default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
        return !this.canRead(clazz, (MediaType)null) && !this.canWrite(clazz, (MediaType)null) ? Collections.emptyList() : this.getSupportedMediaTypes();
    }
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}

getSupportedMediaTypes 定义支持的媒体类型(如:application/json)

canRead/canWrite:判断是否支持读写操作

read/write:执行具体的数据转换逻辑

springboot默认提供的转换器

Spring Boot 自动配置了以下常用消息转换器:

  1. StringHttpMessageConverter - 处理文本数据
  2. MappingJackson2HttpMessageConverter - 处理 JSON 数据(使用 Jackson)
  3. FormHttpMessageConverter - 处理表单数据
  4. ByteArrayHttpMessageConverter - 处理字节数组
  5. ResourceHttpMessageConverter - 处理资源文件
  6. Jaxb2RootElementHttpMessageConverter - 处理 XML(使用 JAXB)
  7. AllEncompassingFormHttpMessageConverter - 增强的表单处理器

springboot在启动的时候就会自动注册上述默认的转换器,有请求进来的时候会根据请求的accept和响应的Content-Type,选择匹配的转换器,若多个转换器都支持,则按注册顺序优先。

如何自定义消息转换器

比如自定义个fastjson转换器

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.NonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    private final FastJsonConfig fastJsonConfig = new FastJsonConfig();
    public FastJsonHttpMessageConverter() {
        // 支持多种媒体类型
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(new MediaType("application", "*+json"));
        setSupportedMediaTypes(supportedMediaTypes);
        // 配置FastJson
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
    }
    @Override
    protected boolean supports(@NonNull Class<?> clazz) {
        return true; // 支持所有类型
    }
    @Override
    protected Object readInternal(
            @NonNull Class<?> clazz,
            @NonNull HttpInputMessage inputMessage
    ) throws IOException, HttpMessageNotReadableException {
        try (InputStream in = inputMessage.getBody()) {
            return JSON.parseobject(
                    in,
                    fastJsonConfig.getCharset(),
                    clazz,
                    fastJsonConfig.getFeatures()
            );
        } catch (Exception e) {
            throw new HttpMessageNotReadableException(
                    "JSON parse error: " + e.getMessage(),
                    inputMessage
 js           );
        }
    }
    @Override
    protected void writeInternal(
            @NonNull Object object,
            @NonNull HttpOutputMessage outputMessage
    ) throws IOExceptwww.devze.comion, HttpMessageNotWritableException {
  编程      try (OutputStream out = outputMessage.getBody()) {
            JSON.writeTo(
                    out,
                    object,
                    fastJsonConfig.getCharset(),
                    fastJsonConfig.getFeatures(),
                    fastJsonConfig.getFilters(),
                    fastJsonConfig.getDateFormat(),
                    JSON.DEFAULT_GENERATE_FEATURE,
                    fastJsonConfig.getWriterFeatures()
            );
        } catch (Exception e) {
            throw new HttpMessageNotWritableException(
                    "JSON write error: " + e.getMessage(),
                    e
            );
        }
    }
    public FastJsonConfig getFastJsonCowww.devze.comnfig() {
        return fastJsonConfig;
    }
    public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
        this.fastJsonConfig.setDateFormat(fastJsonConfig.getDateFormat());
        this.fastJsonConfig.setCharset(fastJsonCHKakCnonfig.getCharset());
        this.fastJsonConfig.setFeatures(fastJsonConfig.getFeatures());
        this.fastJsonConfig.setReaderFeatures(fastJsonConfig.getReaderFeatures());
        this.fastJsonConfig.setWriterFeatures(fastJsonConfig.getWriterFeatures());
        this.fastJsonConfig.setFilters(fastJsonConfig.getFilters());
    }
}

注册自定义的消息转换器 

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class FastJsonWebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建FastJson消息转换器
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        // 可以在这里进一步配置FastJson
        // fastJsonConverter.getFastJsonConfig().setDateFormat("yyyy-MM-dd");
        // 将FastJson转换器添加到转换器列表的最前面
        converters.add(0, fastJsonConverter);
    }
}

注意这里优先级的问题,要把fastjson的放前面,这样才会优先走咱自定义的fastjson的转换器,而不是默认的gson的

到此这篇关于聊聊springboot中如何自定义消息转换器的文章就介绍到这了,更多相关springboot 消息转换器内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜