Skip to main content

Posts

Showing posts from June 12, 2021

Why you should not use field injection

 Greetings! While doing code reviews, I usually come across DI framework (ex: Spring) managed beans with no constructor. I myself have done this many times (and still for POCs). What you can see in these classes is, fields are annotated with @Autowired, @Resource, @Inject, etc. How do they write unit tests then? They will for example use @InjectMocks using mock framework. As I am not a fan of this approach I ask the reasons why are you creating classes like this and use constructors. However, many will not agree with me giving these kinds of reasons. Reasons to use field injection We are using a DI framework (Spring), do not need to worry about this. The unit testing framework we use support field mocking (InjectMocks). We can use reflection in unit tests. Different developers have different practices, you need to accept that fact and respect them. This is how the previous developer coded. This is how our internal framework use. I'm senior than you, do as I say :P. While those can