Inversion of Control and Dependency Injection (English)

Z FI WIKI
Přejít na: navigace, hledání
Tato stránka je dostupná také v češtině: Inversion of Control and Dependency Injection

Motivation

In early days, programs themselves were used to control every aspect of functionality. Good example for this is user interface(UI). Programs used to have a sequence of commands, which would invoke event handlers written directly into your program (Fowler 2012). User interface framework would contain a main loop where these handlers ran.

Nowadays, the trend in frameworks is to divert the control from framework itself into the container, hence the term Inversion of Control (IoC). Developers still have to provide all the functionality, though they just have to use the right annotation and the container will find and provide the component or functionality needed all by itself. The program structure becomes simpler and better decoupling is available for shared features. With IoC is the object coupling completed only during runtime, and is typically not known during the compilation.

The term Dependency Injection and its meaning

Inversion of Control is a very generic term, which is not clear and a lot of people got confused by it. In reaction to this Martin Fowler discussed this problematic with various IoC advocates in 2004 and they finally settled on name Dependency Injection (http://www.martinfowler.com/bliki/POJO.html). The term Dependency Injection is much clearer, because the framework injects the needed functionality (dependency) right where it is needed and programmer only has to specify what and where does he want to have injected.

The injection itself can be done by simple code such as :

 
 
    Player player = 
         (Player) container.lookup("Player");
 

Since Java 1.5 ( also referred to as Java SE 5) programmer is allowed to use annotation such as

                  
    @Autowired

and the container(application server/EJB container) looks up the implementation needed and injects it thus facilitating developers work and making the code less verbose.

References

M. Fowler. Patterns of Enterprise Application Architecture. Addison-Wesley Signature Series. Pearson Education, 2012.

Martin Fowler. Inversion of contorl and dependency injection. http://martinfowler.com/articles/injection.html, 2013.