Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure 2 different MessageConverters for 2 Controllers

I would like to configure two different HttpMessageConverters having the same MediaType for two separate controllers. The reason is that there are some external services that uses different JSON formats. We are not able to change them.

Is it possible? Can I create two WebMvcConfigurerAdapters and split the traffic somehow? If possible, is it a good practice?

like image 624
Marek Raki Avatar asked Dec 19 '25 12:12

Marek Raki


1 Answers

Finally, I solved the problem by overriding MessageConverter adding possiblity to configure its jaxbcontext and assign supported packages. So, then I can create 2 different MesssageConverters for the same controller and depending on a return class use one or another.

public class MoxyMessageConverter extends AbstractHttpMessageConverter<Object> {

  private final JAXBContext jAXBContext;

  private String[] supportedPackages = { ... }; // some defaults

  public MoxyMessageConverter(JAXBContext jAXBContext) {
    this.jAXBContext = jAXBContext;
  }

  public String[] getSupportedPackages() {
    return supportedPackages;
  }

  public void setSupportedPackages(String[] supportedPackages) {
    this.supportedPackages = supportedPackages;
  }

  @Override
  protected boolean supports(Class<?> clazz) {
    String packageName = clazz.getPackage().getName();
    for (String supportedPackage : supportedPackages) {
      if (packageName.startsWith(supportedPackage))
        return true;
    }
    return false;
  }

@Override
  protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
..
}

 @Override
  protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
.. 
}
}

and in the @Configuration class:

@Configuration
@EnableWebMvc
@EnableTransactionManagement
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.extendMessageConverters(converters);
    MoxyMessageConverter defaultMessageConverter = new MoxyMessageConverter(defaultJAXBContext);
    defaultMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices" });
    converters.add(0, defaultMessageConverter );

    MoxyMessageConverter payUMessageConverter = new MoxyMessageConverter(payUJAXBContext);
    payUMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices.payu" });
    converters.add(0, payUMessageConverter);
  }
}
like image 196
Marek Raki Avatar answered Dec 21 '25 04:12

Marek Raki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!