[Spring] Should I have a custom Objectmapper as a static attribute in my service class?
Currently have an Objectmapper, from the JSON jackson serialization api, from my configuration class used in my Service class. Using lombok, realized the @AllArgsConstructor doesn't create a constructor for static attributes.
It makes sense to have it be static in the conventional sense, since it should be shared between service instances.
It is making it hard to do unit tests. As best practice, should I be having the objectmapper attribute in my service class be static or not?
I'm thinking I can forgo making it static since I'm getting a universal Objectmapper from the spring context anyway.
Would appreciate the help.
10 Replies
⌛
This post has been reserved for your question.
Hey @Ghostyjangle! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
Why should a constructor initialize static fields via a parameter? Then they would be overwritten every time you create a new instance
from the docs of
ObjectMapper
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html If you want to share the same configuration for all instances and never change its configuration afterwards, you can make the
ObjectMapper
static
and you probably want to initialize it in a static
initializer block or similar
or
oh sorry I forgot to mention that I want to have spring autowire the objectmapper instance to my service class. Or is this not the way I should do it?
in that case, don't make it
static
But isn't it normally the case that service classes are singletons?I see it as being such that I can just change the objectmapper for some reason, I can just change it in the designated spring config class
fundamentally its weird for objmapper to not be static from what you mentioned, but other than that, are there any implications that I'm missing by not making it static?
not really except that it isn't shared
though it could still be shared if you have the same Spring context
you'd just have multiple references to the same
ObjectMapper
you can't use it from static
methods
but it's really not a problem
For Spring specifically, it's fine to make it non-static
ah right, I'll keep a note on that then, thanks for the help.
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
I'll close the post
Post Closed
This post has been closed by <@294662716684107787>.