How do I correctly reuse Jackson ObjectMapper?

前端 未结 4 455
耶瑟儿~
耶瑟儿~ 2021-02-01 12:10

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

4条回答
  •  醉梦人生
    2021-02-01 12:23

    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.

提交回复
热议问题