如何配置由spring-hateoas注册的MappingJackson2HttpMessageConverter

时间:2014-07-11 09:30:33

标签: java json spring spring-mvc spring-hateoas

我喜欢在我的项目中使用spring-hateoas并使用@EnableHypermediaSupport进行配置。 现在的问题是,这个神奇的配置注释会注册自己的MappingJackson2HttpMessageConverter,我的自定义转换器将被忽略。

背景:我在项目中添加了一些Jackson模块(如JodaModule),我希望它们能够使用objectMapper.findAndRegisterModules();进行注册。这可以通过覆盖configureMessageConverters(List<HttpMessageConverter<?>> converters)WebMvcConfigurationSupport中的WebMvcConfigurer来完成。

我目前的配置如下:

@Configuration
@EnableHypermediaSupport(type = HAL)
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

  @Override
  protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.getObjectMapper().findAndRegisterModules();

    converters.add(converter);
  }
}

有没有办法自定义spring-hateoas使用的MappingJackson2HttpMessageConverterObjectMapper

3 个答案:

答案 0 :(得分:1)

我必须做同样的事情。有了HATEOAS .16,我能够正常工作......但真的很难看。

关键是在HypermediaSupportBeanDefinitionRegistrar中,注册HAL转换器的部分在尝试添加另一个之前检查是否已经存在HAL转换器。所以我自己在我的WebMVCConfig :: configureMessageConverters中添加了一个HAL Converter。

类似的东西:

private static final String DELEGATING_REL_PROVIDER_BEAN_NAME = "_relProvider";
private static final String LINK_DISCOVERER_REGISTRY_BEAN_NAME = "_linkDiscovererRegistry";
private static final String HAL_OBJECT_MAPPER_BEAN_NAME = "_halObjectMapper";

@Autowired
private ListableBeanFactory beanFactory;

private static CurieProvider getCurieProvider(BeanFactory factory) {

    try {
        return factory.getBean(CurieProvider.class);
    } catch (NoSuchBeanDefinitionException e) {
        return null;
    }
}

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        List<HttpMessageConverter<?>> baseConverters = new ArrayList<HttpMessageConverter<?>>();
        super.configureMessageConverters(baseConverters);

        //Need to override some behaviour in the HAL Serializer...so let's make our own
        CurieProvider curieProvider = getCurieProvider(beanFactory);
        RelProvider relProvider = beanFactory.getBean(DELEGATING_REL_PROVIDER_BEAN_NAME, RelProvider.class);
        ObjectMapper halObjectMapper = beanFactory.getBean(HAL_OBJECT_MAPPER_BEAN_NAME, ObjectMapper.class);

        halObjectMapper.registerModule(new Jackson2HalModule());
        halObjectMapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(relProvider, curieProvider));

        MappingJackson2HttpMessageConverter halConverter = new TypeConstrainedMappingJackson2HttpMessageConverter(
            ResourceSupport.class);
        halConverter.setSupportedMediaTypes(Arrays.asList(HAL_JSON));
        halConverter.setObjectMapper(halObjectMapper);

        converters.add(halConverter);
    }

这显然取决于实现,使用实现细节,并且实际上不允许您修改@EnableHyperMediaSupport为您构建的那个....但它现在有效。

答案 1 :(得分:0)

我使用以下方法

@Configuration
@EnableHypermediaSupport(type = HypermediaType.HAL)
public class MvcConfig {    

  @Bean
  public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {

答案 2 :(得分:0)

我为我的问题找到了一个丑陋的解决方案:

我正在使用BeanPostProcessor和大量的反射魔法,用我自己的一个替换Spring HATEOAS的内部ConversionService,之前已经添加到Spring上下文中。这样我确保Spring HATEOAS使用与Spring MVC完全相同的ConversionService。

/**
 * This is a HACK to work around a not yet implemented feature. At the moment Spring Hateoas uses a
 * {@link ConversionService}, which is hold in a private static final field and hence cannot be accessed to add more
 * Converters<br/>
 *
 * <ul>
 *   <li><a href="https://github.com/spring-projects/spring-hateoas/issues/118">Spring Hateoas Issue</a></li>
 *   <li><a
 *     href="http://stackoverflow.com/questions/22240155/converter-from-pathvariable-domainobject-to-string-using-controllerlinkbuilde">
 *     Solution on Stackoverflow</a></li>
 * </ul>
 */
public static class HateoasConversionServicePostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
        if (bean instanceof ConversionService) {
            try {
                Class<?> clazz = Class.forName(
                        "org.springframework.hateoas.mvc.AnnotatedParametersParameterAccessor$BoundMethodParameter");
                Field field = clazz.getDeclaredField("CONVERSION_SERVICE");
                field.setAccessible(true);

                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

                field.set(null, bean);

                modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
        return bean;
    }
}