spring 5 webflux中以下spring mvc代码的等效配置是什么?如何在webflux中添加多个转换器?
<li>
答案 0 :(得分:0)
我发现,如果仅将YAML HttpMessageConverter
注册为bean webflux,它将自动使用它。
答案 1 :(得分:0)
我知道这很久了,但是在挖掘并没有找到答案之后,我终于能够使用大量不同的帖子将它们拼凑在一起,希望在这里帮助未来的人。
/**
* Modelled off of Jackson2JsonDecoder
*/
public class Jackson2YamlDecoder extends AbstractJackson2Decoder {
public Jackson2YamlDecoder() {
super(YAMLMapper.builder().build(), new MimeType("application","x-yaml"));
}
}
/**
* Modelled off of Jackson2JsonEncoder
*/
public class Jackson2YamlEncoder extends AbstractJackson2Encoder {
@Nullable
private final PrettyPrinter ssePrettyPrinter;
public Jackson2YamlEncoder() {
super(YAMLMapper.builder().build(), new MimeType("application","x-yaml"));
this.ssePrettyPrinter = initSsePrettyPrinter();
}
private static PrettyPrinter initSsePrettyPrinter() {
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(new DefaultIndenter(" ", "\ndata:"));
return printer;
}
@Override
protected ObjectWriter customizeWriter(ObjectWriter writer, MimeType mimeType, ResolvableType elementType, Map<String, Object> hints) {
return this.ssePrettyPrinter != null && MediaType.TEXT_EVENT_STREAM.isCompatibleWith(mimeType) && writer.getConfig().isEnabled(SerializationFeature.INDENT_OUTPUT) ? writer.with(this.ssePrettyPrinter) : writer;
}
}
@Configuration
public class WebFluxConfig implements WebFluxConfigurer {
@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
CodecConfigurer.CustomCodecs customCodecs = configurer.customCodecs();
customCodecs.registerWithDefaultConfig(new Jackson2YamlDecoder());
customCodecs.registerWithDefaultConfig(new Jackson2YamlEncoder());
}
}