I am happy with how the ObjectMapper works and general use within my application. What I would like to understand is the best way to implement the ObjectMapper to ensure it is r
The plain static singleton you proposed in your question is correct. An alternative approach would be to use the singleton pattern (the use of singleton pattern been discussed at length in answer comments to a similar question). Here's a simple example:
public enum Mapper {
INSTANCE;
private final ObjectMapper mapper = new ObjectMapper();
private Mapper(){
// Perform any configuration on the ObjectMapper here.
}
public ObjectMapper getObjectMapper() {
return mapper;
}
}
Then you can use (and reuse) the ObjectMapper
singleton as follows:
ObjectMapper mapper = Mapper.INSTANCE.getObjectMapper();
JsonSimple jsonSimple = mapper.readValue(jsonString, JsonSimple.class);
This is safe as ObjectMapper
is thread-safe after configuration.
Caveat: As @StaxMan points out in the answer comments, this does NOT guarantee against further (re)configuration on the returned singleton.