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?
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);
}
}