What is Dependency Injection?

Dependency injection is a concept valid for any programming language. The general concept behind dependency injection is called Inversion of Control. According to this concept, a class should not configure its dependencies statically but should be configured from the outside.

A Java class has a dependency on another class if it uses an instance of this class. We call this a _class dependency. For example, a class which accesses a logger service has a dependency on this service class.

Ideally, Java classes should be as independent as possible from other Java classes. This increases the possibility of reusing these classes and to be able to test them independently from other classes.

If the Java class creates an instance of another class via the new operator, it cannot be used (and tested) independently from this class and this is called a hard dependency. The following example shows a class which has no hard dependencies.

package com.jithin88.example.di;

import java.util.logging.Logger;

public class MyClass {

    private final static Logger logger;

    public MyClass(Logger logger) {
        this.logger = logger;
        // write an info log message
        logger.info("This is a log message.")
Please note that this class is just a normal Java class, there is nothing special about it, except that it avoids direct object creation.

A framework class, usually called the dependency container, could analyze the dependencies of this class. With this analysis, it is able to create an instance of the class and inject the objects into the defined dependencies, via Java reflection.

This way the Java class has no hard dependencies, which means it does not rely on an instance of a certain class. This allows you to test your class in isolation, for example by using mock objects.

Mock objects (mocks) are objects which behave similarly as the real object. But these mocks are not programmed; they are configured to behave in a certain predefined way. Mock is an English word which means to mimic or to imitate.

If dependency injection is used, a Java class can be tested in isolation.

Popular posts from this blog

Async Task in Android

Shake effect in Android

Example For ListView Using BaseAdapter