聊聊springboot中如何自定义消息转换器
作者:白衣神棍
SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍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 自动配置了以下常用消息转换器:
- StringHttpMessageConverter - 处理文本数据
- MappingJackson2HttpMessageConverter - 处理 JSON 数据(使用 Jackson)
- FormHttpMessageConverter - 处理表单数据
- ByteArrayHttpMessageConverter - 处理字节数组
- ResourceHttpMessageConverter - 处理资源文件
- Jaxb2RootElementHttpMessageConverter - 处理 XML(使用 JAXB)
- 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
);
}
}
@Override
protected void writeInternal(
@NonNull Object object,
@NonNull HttpOutputMessage outputMessage
) throws IOException, 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 getFastJsonConfig() {
return fastJsonConfig;
}
public void setFastJsonConfig(FastJsonConfig fastJsonConfig) {
this.fastJsonConfig.setDateFormat(fastJsonConfig.getDateFormat());
this.fastJsonConfig.setCharset(fastJsonConfig.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 消息转换器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
