如果想自定义传输数据的类型 需要设置自己的messageConverter
public class YanMessageConverter implements HttpMessageConverter {
@Override
public boolean canRead(Class clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class clazz, MediaType mediaType) {
return clazz.isAssignableFrom(Car.class);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
MediaType mediaType = MediaType.parseMediaType("application/yan");
ArrayList<MediaType> objects = new ArrayList<>();
objects.add(mediaType);
return objects;
}
@Override
public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
Car o1 = (Car) o;
String data="hello "+((Car) o).getName()+" hello "+((Car) o).getPrice();
OutputStream body = outputMessage.getBody();
String s = new String(data.getBytes(), "UTF-8");
System.out.println(s);
body.write(s.getBytes("gbk"));
}
}
@Import(User.class)
@Configuration(proxyBeanMethods = true)
@EnableConfigurationProperties(Car.class)
public class MyConfiguration implements WebMvcConfigurer {
@Bean
@ConditionalOnClass(name = "Pet")
public User getUser(){
return new User("yan",18,getPet());
}
public Pet getPet(){
return new Pet("tom");
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new Converter<String, Pet>() {
@Override
public Pet convert(String source) {
String[] split = source.split(",");
return new Pet(split[0]);
}
});
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
HashMap<String, MediaType> stringMediaTypeHashMap = new HashMap<>();
stringMediaTypeHashMap.put("xml",MediaType.APPLICATION_XML);
stringMediaTypeHashMap.put("json",MediaType.APPLICATION_JSON);
stringMediaTypeHashMap.put("yan",MediaType.parseMediaType("application/yan"));
ParameterContentNegotiationStrategy parameterContentNegotiationStrategy = new ParameterContentNegotiationStrategy(stringMediaTypeHashMap);
HeaderContentNegotiationStrategy headStrategy=new HeaderContentNegotiationStrategy();
configurer.strategies(Arrays.asList(parameterContentNegotiationStrategy,headStrategy));
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new YanMessageConverter());
}
}