1

What will be the equivalent configuration of below spring mvc code in spring 5 webflux? how can i add multiple converters in webflux?

@Configuration
public class YamlConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new YamlJackson2HttpMessageConverter());
    }
}

final class YamlJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {
    YamlJackson2HttpMessageConverter() {
        super(new YAMLMapper(), MediaType.parseMediaType("application/x-yaml"));
    }
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

2 Answers2

1

I know this is old, but after digging and finding no answers, I was finally able to piece this together using a bunch of different posts, posting here in hopes of helping future people.

/**
 * 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());
    }
}
Marcus
  • 55
  • 7
0

I found that if you just register the YAML HttpMessageConverter as a bean webflux will automatically use it.

Rob Fletcher
  • 8,317
  • 4
  • 31
  • 40