1、自定义消息转换器MessageConverter
在WebMvcAutoConfiguration类中有一个方法configureMessageConverters(),它会配置默认的MessageConverter
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
this.messageConvertersProvider.ifAvailable((customConverters) -> {
converters.addAll(customConverters.getConverters());
});
}
假设我们现在有一个新的需求
想要后端返回我们自己定义的格式的数据,就叫x-decade,格式为使用分号拼接Person对象属性值
那么就要新建一个MessageConverter了
package com.decade.converters;
import com.decade.pojo.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
public class DecadeConverter implements HttpMessageConverter<Person> {
// 只考虑写出,所以这里默认写false
@Override
public boolean canRead(Class<?> clazz,