8

Mapper instances are fully thread-safe, there is no need to create a mapper for single use, but mapper's config can be changed.

Although ObjectMapper has copy function to duplicate the config for customize based on exists mapper, if I share a mapper, there is no guarantee that when someone want to customize the mapper, they will copy the shared mapper. So I want a immutable mapper to share, if someone accidently changed the shared mapper, some exception should be throw.

Is there something like this ?

wener
  • 7,191
  • 6
  • 54
  • 78
  • I will create a wrapper of ObjectMapper and just public some needed functions – Viet Apr 26 '17 at 08:06
  • On the contrary, I just want to hide some function to prevent config change, this seems very common use case, is there any exists wrapper for this ? If no, I will create one for myself. – wener Apr 26 '17 at 08:13
  • One option could be to share an `ObjectWriter` instance instead of an `ObjectMapper`. That class appears at first glance to be immutable, although I believe it's not the intended purpose of it. – Henrik Aasted Sørensen Apr 26 '17 at 10:03
  • @Henrik But from ObjectWriter can not clone a ObjectMapper. – wener Apr 26 '17 at 10:17
  • @wener: You shouldn't need to do that. Create a correctly configured `ObjectMapper` and then provide instances of `ObjectReader` and `ObjectWriter` to the parts of the code where you're afraid someone might change the configuration. See this answer for more details : http://stackoverflow.com/a/3909846/13075 – Henrik Aasted Sørensen Apr 26 '17 at 10:22
  • @Henrik Thanks! If there is no immutable `ObjectMapper`, use immutable `ObjectReader` or `ObjectWriter` instead. – wener Apr 26 '17 at 10:26
  • @wener: No problem. Just learned this myself during research. :) – Henrik Aasted Sørensen Apr 26 '17 at 10:27

1 Answers1

7

One approach is to not share the ObjectMapper instance, but rather configure it correctly and then share instances of ObjectWriter and ObjectReader created by the ObjectMapper.

ObjectMapper om = new ObjectMapper();
// Configure to your needs
om.enable(...);
om.disable(...);

// Distribute these to the parts of the program where you fear configuration changes.
ObjectWriter writer = om.writer();
ObjectReader reader = om.reader();

This also seems to be the approach favoured by the developers of Jackson: https://stackoverflow.com/a/3909846/13075

Community
  • 1
  • 1
Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60