Pascal
Pascal

Reputation: 2154

Spring return image from controller while using Jackson Hibernate5Module

I am using Spring 4.3.1 and Hibernate 5.1.0 for my webapp. For Jackson to be able serializing lazy objects I have to add the Hibernate5Module to my default ObjectMapper. This I have done via

@EnableWebMvc
@Configuration
@ComponentScan({ "xxx.controller" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

        @Autowired
        SessionFactory sf;

...

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

                Hibernate5Module module = new Hibernate5Module(sf);
                module.disable(Feature.USE_TRANSIENT_ANNOTATION);
                module.enable(Feature.FORCE_LAZY_LOADING);

                Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
                builder.modulesToInstall(module);

                converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
                super.configureMessageConverters(converters);

        }

}

This is working but if it is enabled serializing a byte[] does not work anymore and fails with HTTP Status 500 - Could not write content: No serializer found for class java.io.BufferedInputStream

So my question is how to extend the default ObjectMapper while preserving the default ones?

I have seen somthing preserving the defaults using Spring Boot but I do not use Spring Boot. Any ideas?

Upvotes: 0

Views: 270

Answers (1)

Alexander
Alexander

Reputation: 2888

As specified in the WebMvcConfigurer.configureMessageConverters javadoc, "If no converters are added, a default list of converters is registered", i.e. you will have to manually add all the default converters if you are using WebMvcConfigurer. Calling 'super.configureMessageConverters(converters)' does nothing if you extend WebMvcConfigurer. Take a look in 'WebMvcConfigurationSupport.addDefaultHttpMessageConverters(...)' to see all the default message converters, you can also extend this class instead of WebMvcConfigurer, with which you get slightly more clarity what happens.

Upvotes: 1

Related Questions