Skip to main content

Posts

Showing posts from September, 2022

Why is it better to use Spring Constructor injection?

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 ...