springBoot 消息转换器和自定义消息转换器
public interface HttpMessageConverter<T> {/*** 能否以指定的类读取*/boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);/*** 能否以指定的类写*/boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);/*** 返回支持是消息转换器的媒体列表*/List<MediaType> getSupportedMediaTypes();/*** Return the list of media types supported by this converter for the given* class. The list may differ from {@link #getSupportedMediaTypes()} if the* converter does not support the given Class or if it supports it only for* a subset of media types.* @param clazz the type of class to check* @return the list of media types supported for the given class* @since 5.3.4*/default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {return (canRead(clazz, null) || canWrite(clazz, null) ?getSupportedMediaTypes() : Collections.emptyList());}/*** 将输入的内容读成指定的类型并返回*/T read(Class<? extends T> clazz, HttpInputMessage inputMessage)throws IOException, HttpMessageNotReadableException;/*** 将给定的内容写成指定的类型*/void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)throws IOException, HttpMessageNotWritableException;}
由此可见,可根据游览器接受类型和服务器生产类型,返回不同的数据类型:
①定义游览器可以接受的数据类型:
例如:
Accept:text/html,application/xhtml+xml,application/xml
②服务器引入可生产的数据类型的jar或自定义消息转换器
例如:引入可生产xml消息类型的jar包
扩展:自定义消息转换器
一、通过实现接口:WebMvcConfigurer
@Configuration public class BootConfig implements WebMvcConfigurer {/*** 自定义参数转换*/@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(new Converter<String, Integer>() {@Overridepublic Integer convert(String source) {return null;}});}/****/@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new MyMessageConver());} }
二、通过注册Bean
@Bean public WebMvcConfigurer webMvcConfigurer() {return new WebMvcConfigurer() {/*** 添加自定义格式化器或转换器** @param registry*/@Overridepublic void addFormatters(FormatterRegistry registry) {//Converter<S, T> S源类型,T目标类型registry.addConverter(new MyConverter());}/*** 扩展消息转换器*/@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new MyMessageConver());}}; }