Posts

Showing posts from January, 2015

Dependency injection pitfalls in Spring

There are three injection variants in Spring framework:
Setter-based injectionConstructor-based injectionField-based injection Each of those mechanisms has advantages and disadvantages and there is not only one right approach. For example field injection: @Autowired private FooBean fooBean; It's generally not the best idea to use it in the production code, mostly because it makes our beans impossible to test without starting Spring context or using reflection hacks. On the other hand it requires almost no additional code and could be used in integration tests - which definitely won't be instantiated independently. And in my opinion this is the only case for field-based injections.

Now let's focus on two major variants. In Spring documentation we can read that
...it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Also in documentation referring Spring up to 3.1 we could find a sentence
The Spring team gene…