This has been one of the common interview questions for senior engineers for the Java Spring framework. I was pondering this question myself for a while about the pros and cons of using the constructor injections.
Spring framework provides the means for dependency injections using 3 ways using annotations (@Autowired).
- Constructor injection
- Field injection
- Setter injection
Out of these 3, the Field injections and Setter, injections are somewhat similar, but field injections are more commonly used than the Setter injections. I believe that is due to the fact that it is more convenient to use and implementing setters are kind of automated using libraries such as Lombok.
I can think of a couple of reasons to use Constructor injections over Field injections.
1. Immutability
Using constructor injections, it buys us immutable objects of the dependent class. Whereas if the Fields or Setters were used, they can be modified during the runtime which would make it not exactly thread-safe. Having immutable objects makes it safer to use in a multi-threaded environment. Also, using the final keyword to define the dependencies of instance variables would guarantee that it would be forced to assign a value within the constructor.
2. Prevent NullPointerException
It could be a common mistake forgetting to instantiate some objects or having the beans created for them to be used as dependencies. Using constructor injections makes it compulsory to have the beans created properly before using them.
I still couldn't find any facts to support that it would make it run faster nor it will reduce the memory footprint.
Comments
Post a Comment