spring-projects / spring-hateoas

Spring HATEOAS - Library to support implementing representations for hyper-text driven REST web services.
https://spring.io/projects/spring-hateoas
Apache License 2.0
1.03k stars 475 forks source link

MappingJackson2HttpMessageConverter and _halObjectMapper not working with spring-hateos 2.0.1 and spring boot 3 #1961

Open anishsharma opened 1 year ago

anishsharma commented 1 year ago

We have a legacy app which we are updating to spring boot 3. We used to use spring-hateos 0.24 RELEASE and below code to register MappingJackson2HttpMessageConverter.

public static class RestServicesConfiguration implements WebMvcConfigurer  {

       @Override
        public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {

            converters.add(jsonConverter());
            this.configureMessageConverters(converters);
        }

       @Bean
        public MappingJackson2HttpMessageConverter jsonConverter() {
            final MappingJackson2HttpMessageConverter converter = new HalMappingJackson2HttpMessageConverter();
            return converter;
        }

private class HalMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

            private HalMappingJackson2HttpMessageConverter() {
                setSupportedMediaTypes(Arrays.asList(
                        CURRENT_REST_VERSION_MEDIA_TYPE,
                        PREVIOUS_REST_VERSION_MEDIA_TYPE,
                        V2_REST_VERSION_MEDIA_TYPE
                ));
                final ObjectMapper halObjectMapper = (ObjectMapper) beanFactory.getBean("_halObjectMapper");

                final SimpleModule module = new SimpleModule("MySerializers");
                module.addSerializer(Date.class, new DateSerializer());
                halObjectMapper.registerModule(module);

                setObjectMapper(halObjectMapper);
            }
        }

As we have updated to spring-hateos 2.0.1 via spring-boot-starter-data-rest 3.0.2. Upon running executing the WAR file in Tomcat 10 we are getting below exception.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jsonConverter' defined in com.config.AppInitializer$RestServicesConfiguration: Failed to instantiate [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter]: Factory method 'jsonConverter' threw exception with message: No bean named '_halObjectMapper' available

odrotbohm commented 1 year ago

The customization model has changed significantly in 1.0 already. Jumping from 0.24 to 2.0 is quite a leap. That said, you should be able to simply declare a bean of type HalConfiguration, call ….withObjectMapperCustomizer(…) on it and apply your customizations there. Additional media types can be registered via ….withMediaType(…).