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.

No alt text provided for this image

This is what field injection looks like.

Problems with field injection

  1. Fields defining the state of an object are hidden and objects can be created with an inconsistent state and the risk of NullPointerExceptions being thrown.?
  2. It makes classes more difficult to test (especially when writing unit tests). So if you want to test a small functionality in a class, and the injected field is declared private and there is no setter for it, you would not be able to inject a stub or a mock implementation. Well, you can argue that there is always reflection, and testing libraries like Mockito provide utility methods to avoid the reflection boilerplate, but that should not even be considered for many reasons (performance and security), also because starting with modules in Java 9, it become trickier as hell.?Field injection is done using reflection, as it is the only way to access a private field in Java, which obviously lead to a slow performance so, avoid using it unless you really have no other choice.?

This leads us to ask ourselves a question, when can we use field injection?

  • @Configuration classes: To inject infrastructure beans that are created by the Spring IoC container and you want to customise them.
  • Test classes: The tested bean should be injected using field injection as it keeps things readable.?At this stage you don't really worry about performance.
  • When you find yourself in a code base that is burdened with field injection, you might as well do what the romans do.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了