How to get access to the global spring ObjectMapper?
I am working on a spring boot application. I have the below utility class which does conversion from a string to Json object.
public class JsonParser {
private static ObjectMapper objMapper;
private static ObjectMapper getMapper() {
if (objMapper == null) {
objMapper = new ObjectMapper();
}
return objMapper;
}
public static <K> K fromJsonToObj(String json, Class<K> kClass) throws IOException {
return mapper.readValue(json, kClass);
}
}
And in one of my classes I am using it as below
User user = JsonParser.fromJsonToObj(jsonString, User.class);
But I was told that above approach is not a very good practice,
The best practices for the Jackson Objectmapper suggest only a single instance of the mapper should be created within the application. Part of spring uses jackson to deserialize and serialize the request body attached to requests, so it already has one. To allow Jackson’s best practices to be followed, spring exposed the ObjectMapper as a bean so it can be accessed in other locations. We want to use this object mapper rather than create our own. This also allows us to configure a single object mapper rather than configure multiple object mappers in case we need additional configurations on top of base ObjectMapper.
So if we do need an objectMapper in a static utils class, we should pass in the object mapper as a param and in the service layer or anywhere else, we can use:
@Autowired
private ObjectMapper objectMapper;
to get the global spring object mapper.
But I am not sure how to go about with this above suggested approach. Can anyone throw light on what is the correct way? Are there any configurations that I need to provide.
from Recent Questions - Stack Overflow https://ift.tt/3kJzx7G
https://ift.tt/eA8V8J
Comments
Post a Comment