0
votes

I'm using Spring Boot 2. I'd like to define a singleton bean of type MappingJackson2HttpMessageConverter, which will be used only by other beans.

By default, Spring Boot picks up a user defined MappingJackson2HttpMessageConverter and replaces the default instance with the one provided by the user, as stated by official documentation (https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper):

If you provide any @Beans of type MappingJackson2HttpMessageConverter, they replace the default value in the MVC configuration. Also, a convenience bean of type HttpMessageConverters is provided (and is always available if you use the default MVC configuration). It has some useful methods to access the default and user-enhanced message converters.

This is my configuration class:

@Bean
public MappingJackson2HttpMessageConverter myJacksonConverter() {
...
}

@Bean
@Scope("prototype")
public MyClient myClient(){
     MyClient c = new MyClient();
     c.setConverter(myJacksonConverter());
     return c;
}

So, I want MappingJackson2HttpMessageConverter as a singleton bean, but I don't want that Spring Boot uses it at global application level.

3
Why does your bean have to be a MappingJackson2HttpMessageConverter? Can't it just be a custom subclass of AbstractJackson2HttpMessageConverter? - Andreas

3 Answers

2
votes

I'd consider not defining your custom converter as a @Bean. Instead, you could create your custom converter and store it in a field of a @Configuration class and then reference it from there. The @Configuration class will only be created once so you're guaranteed to only get a single instance of your custom converter.

0
votes

If it is used only inside the same config class, you can avoid to use @Bean annotation.

@Bean
public MyClient myClient(){
     MyClient c = new MyClient();
     c.setConverter(myJacksonConverter());
     return c;
}

private static MappingJackson2HttpMessageConverter myJacksonConverter() {

}
-1
votes

See if this works .. Define a class that extends from MappingJackson2HttpMessageConverter and autowire it.

class MyCustomMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {} 

@Bean
public MyCustomMappingJackson2HttpMessageConverter myJacksonConverter() {
...
}

@Bean
public MyClient myClient(){
     MyClient c = new MyClient();
     c.setConverter(myCustomJacksonConverter());
     return c;
}```