Tag Archives: programming-concept

Dependency Injection

/* Vietnamese: Bài viết này nhằm mục đích giải thích một cách đơn giản nhất khái niệm Dependency Injection – một khái niệm mới mẻ những đã khá phổ biến trong thế giới lập trình hiện nay */

To my readers (if there’s any yet): I have written this blog for a while. At first, it should reflect my learning process – not all, but every post is a mark somehow. For over half of a year, now I think it’s best to make many short posts instead of lengthly ones. Thank all of you for your support.

Dependency Injection is a fairly new concept. Its origin can be traced back to Rod Johnson – the founder of Spring Framework. But we won’t go to history lesson now, let’s skip to the content itself.

The basic idea of “Dependency Injection” lies on the problem: how we should manage the dependency between modules(in the simplest case, object) in a large system.

An object should not initialize its dependencies. Dependencies of an object should be given to it by the environment.

Let’s see the following example:

Naturally, when a module A(Printer) need module B(PaperService), the original OOP thinking styles should produce something like this:


class Printer {

PaperService paperService;

public Printer () {

paperService = new PaperServiceImpl();

}

....

}

But by Dependency Injection way, it should be like this:

 class Printer {

PaperService paperService;

public Printer(PaperServiceImpl service) {

this.paperService = service;

}

...

}