In Dependency Injection, field injection is generally discouraged in favor of constructor argument injection so that one can make the injected field final (immutable). Constructor argument injection also offers a few other conveniences. However, if an injected field is private, or even protected, needing to create a constructor in the subclass feeding a value up into the super class that is otherwise should not be the concern of the subclass, runs contrary to the the beauty of inheritance - a subclass getting the provisions of the parent class. Assuming that there is no subclass-specific value for the field in question, every single subclass would have to just repeat the same constructor code. This can make the code more complex and harder to understand, especially when there are multiple dependencies and multiple levels of inheritance.
public class A {
private final Foo foo;
public A(Foo foo) {
this.foo = foo;
}
}
public class B extends A {
@Autowired
public B(Foo foo) {
super(foo);
}
}
The immutability in the above mainly refers to the prevention of inadvertent reassignment and not necessarily any performance optimization that the final qualifier can impart to the field. In spite of this, some insist that all injected fields must be made final. What are the other pros and cons?