为2个控制器配置2个不同的MessageConverters

时间:2016-04-08 11:19:34

标签: json spring spring-mvc spring-web

我想为两个独立的控制器配置两个具有相同HttpMessageConverters的{​​{1}}。原因是有一些外部服务使用不同的JSON格式。我们无法改变它们。

有可能吗?我可以创建两个MediaType并以某种方式拆分流量吗?如果可能的话,这是一个好习惯吗?

1 个答案:

答案 0 :(得分:0)

最后,我通过重写MessageConverter添加可能性来配置其jaxbcontext并分配支持的包来解决问题。那么,我可以为同一个控制器创建2个不同的MesssageConverters,并根据返回类使用一个或另一个。

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 {
.. 
}
}

并在@Configuration类中:

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