DI pitfalls

As we know, there are three DI patterns in the Spring application: constructor-setter-and field-based. Each type has different advantages and disadvantages. Only field-based DI is an incorrect approach and not even recommended by Spring.

Following is an example of a field-based injection:

@Autowired
private ABean aBean;

As per Spring bean best practices, we should not use field-based dependency in our Spring application. The main reason is that it is impossible to test without Spring context. As we cannot supply the dependency from outside, it will not be possible to instantiate the object independently. As per my opinion, this is the only problem with field-based injections.

As we learned in an earlier section, constructor-based dependency is more suitable for mandatory fields, and we can ensure the immutable nature of the object is obtained; however, the main drawback of a constructor-based dependency is that it creates circular dependency in your application, and as per Spring documentation, it is generally recommended to not rely on circular dependency between your beans. So, now we have questions like, Why not rely on circular dependency? and What will happen if we have a circular dependency in our application? So, the answer to these questions is that it may create two significant and unfortunately silent pitfalls. Let's discuss them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset