Monday, April 2, 2012

Dependency injection

Dependency injection (DI) is an approach to the testing of computer programs, the purpose of which is both to improve the testability of a large software system and to simplify the deployment of software components within that system. DI is an example of a design pattern in object-oriented computer programming.
Dependency injection involves at least three elements:
  • a dependent consumer,
  • a declaration of a component's dependencies, defined as interface contracts,
  • an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request.
The dependent object describes what software component it depends on to do its work. The injector decides what concrete classes satisfy the requirements of the dependent object, and provides them to the dependent.
In conventional software development the dependent object decides for itself what concrete classes it will use. In the dependency injection pattern, this decision is delegated to the "injector" which can choose to substitute different concrete class implementations of a dependency contract interface at run-time rather than at compile time.
Being able to make this decision at run-time rather than compile time is the key advantage of dependency injection. Multiple, different implementations of a single software component can be created at run-time and passed into (injected) the same test code. The test code can then test each different software component without being aware that what has been injected is implemented differently.
There has been several ways of doing dependency injection in your Java application. The idea behind them is well understood, but the actual realization is slightly different.: XML files or property files vs Java annotations or classes. Choosing between which framework to use can become a pretty religious discussion.

In a short time I will write about JSR-300 and why I don't like it.

No comments:

Post a Comment