Dependency Injection
What is dependency injection?

What is dependency injection?

What is dependency injection? This is the first question which comes to the mind of many when they start learning Spring/Seam/Struts framework.

Introduction

Dependency injection is a programming paradigm where programmer do not write code to create the dependency instance, instead instance is created by an external framework. Connecting or “injecting” this dependency into appropriate places is Dependency Injection. There are many dependency injection frameworks and multiple ways to insert the dependencies viz Spring framework, Seam framework etc.

Difference between using Dependency Injection and not using Dependency Injection
Difference between using Dependency Injection and not using Dependency Injection

Without Dependency Injection

Following source code shows the approach of creating dependency instances without dependency injection framework.

public class Main {

    public void run() throws IOException {
        LogWriter logWriter = new FileLogWriter("test.log");
        logWriter.writeLine("test-statement");
        logWriter.close();
    }

}

In above code, we are creating an instance of LogWriter using its implementation FileLogWriter. Client code is aware of the implementation and if we want to update the client code we have to change the code here too.

Using Dependency Injection

Now, if we use dependency injection framework in above code, it would be like following.

@Singleton
public class Main {

    @Inject
    private LogWriter logWriter;

    public void run() throws IOException {
        logWriter.writeLine("test-statement");
    }

}

Above code uses a simple dependency injection framework which loads the beans declared in di.xml file. Following are the contents of di.xml file.

<beans>
    <bean class="com.ts.learning.di.logs.impl.FileLogWriter">
        <contructor-arg>test.log</contructor-arg>
    </bean>
</beans>

Conclusion

So it is clear that if dependency injection framework is used then client code remains unaware of implementations. We can change the client code at any time without worrying about the implementations.

Leave a Reply

Your email address will not be published. Required fields are marked *