[Quick Solution] Add Another Custom ObjectMapper Configuration in Spring Boot

[Issue]

  I have a system that provides Rest APIs using Spring Boot, communicating smoothly with clients via JSON. Recently, I encountered a situation where I needed to communicate with a new server using slightly different JSON communication rules.
  To accommodate this, I added a custom ObjectMapper Bean ("myObjectMapper") to my configuration.
  However, after doing so, the previously functioning Rest APIs started to misbehave, giving the impression that the newly added myObjectMapper was being used even in the existing JSON communications.
@Configuration
public class MyConfiguration {

	@Bean
	ObjectMapper myObjectMapper() {
		ObjectMapper mapper1 = new ObjectMapper();
		mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// ...
		return mapper1;
	}

}


[Solution]

  To address this issue, I added the following Primary Bean configuration for "jacksonObjectMapper" with the annotation @ConditionalOnMissingBean(name = "jacksonObjectMapper") at the top.

  This resolved the issue, and the system returned to normal operation.
@Configuration
public class MyConfiguration {

	@Bean
	@Primary
	@ConditionalOnMissingBean(name = "jacksonObjectMapper")
	ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		return builder.createXmlMapper(false).build();
	}

	@Bean
	ObjectMapper myObjectMapper() {
		ObjectMapper mapper1 = new ObjectMapper();
		mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// ...
		return mapper1;
	}

}


End.


Source: https://m.blog.naver.com/beyond-gem/223454127142 

Comments

Popular posts from this blog

[Simple Note] Select … For Update Options in Oracle (WAIT, NOWAIT, SKIP LOCKED)

[Quick Solution] Naver Blog Broken Issues on Microsoft Edge Mobile Browser