Best practices and anti-patterns
So far, we have talked about using IoC containers to achieve DI, but one of the most common mistakes is to use IoC containers without doing real DI. This may sound strange, but it is a fact. Such mistakes are possible in the absence of having a proper understanding of underlying concepts.
Ideally, DI implementation should only reference the IoC container during the time of the application's startup. If a developer wraps the IoC container itself and passes it into other component to reduce any dependency, this is not a good design. Let's understand this issue with an example.
What to inject – the container itself or just dependencies?
The situation of injecting container occurs when you try to wrap the container itself either in a singleton class or a public static method to provide the dependency to other components or modules, as in the following snippet:
public class AccountService { //Service method. public void getVariablePay() { System.out.println...