Spring Dependency Injection
Dependency Injection
Is an action of supplying dependencies to a dependant bean. Since most of my audience are familiar with this concept, I won't talk more about it to avoid a long article.
Today, a descent number of applications still use field injection to wire dependencies hence motivation for this article. Albeit it seems practical to use field injection as classes are more "readable", using it hides the dependencies of a class. You do not know the dependencies of a class without navigating the source code. No wonder, many people refer to Spring as “magic”. I don't want to lie, as a junior developer, this @Autowired on a field used to make me think spring framework developers are magicians. Little did I know that their "state of the art" field injection wasn't really a that good. You will see as we progress with this article that not all that glitters is gold.
Before we look at the problems with this type of injection, see the image below.
领英推荐
This is what field injection looks like.
Problems with field injection
This leads us to ask ourselves a question, when can we use field injection?