Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom jackson mapper on spring boot endpoints

I want to use different jackson ObjectMapper instance ( instead of the one used on other mapped urls ) on endpoints derived from AbstractEndpoints.

To clarify the question, I don't want to change or customise the object mapper which is used by different urls from the ones derived from AbstractEndpoints ( like HealtEndpoint, MetricsEndpoint ). I want to specifically inject new object mapper into management endpoints.

like image 399
walrus03 Avatar asked Oct 29 '22 12:10

walrus03


2 Answers

If you want to replace the default ObjectMapper completely, either define a @Bean of that type and mark it as @Primary, or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean. Note that in either case this will disable all auto-configuration of the `ObjectMapper.

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

You can read the full topic in the documentation: 73.3 Customize the Jackson ObjectMapper

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper

like image 186
Bocz Tivadar Avatar answered Nov 15 '22 06:11

Bocz Tivadar


As of Spring Boot 1.5 you can customize the ObjectMapper the JMX endpoints are using but not in the way you want. As you can see for example in the constructor of EndpointMBean it takes an ObjectMapper as argument but without any qualifiers. Hence it automatically uses the default ObjectMapper and there's nothing you can do about it except changing the original sources or rolling your own endpoints and adding the necessary qualifiers.

If you still want to use the default endpoints provided by Spring Boot, customize the default ObjectMapper according to your needs, create a second instance that matches the original configuration and add the qualifiers to use the second ObjectMapper in your own code. The customization options for Jackson's ObjectMapper are described in the Spring Boot docs and also discussed in How to customise the Jackson JSON mapper implicitly used by Spring Boot?.

like image 27
aha Avatar answered Nov 15 '22 07:11

aha