Inversion of Control and Dependency Injection
October 9, 2012 Leave a comment
Inversion of control is too broad term for the frameworks to claim that they are based on IoC. It depends on what control of the application are you inverting? Especially with new set of containers or frameworks IoC is about how they lookup and inject a particular 3rd party provided plugins into the application. These container/framework providers ensure that the user follows some conventions that allows separate assembler module (from the container providers) to inject dependencies into their applications.
As a result we now see IoC as too generic name and we need some other specific name to name this and for this reason we came up with Dependency injection (DI).
Let us start with some basic example
public Class StudentLister { private StudentFinder finder; public StudentLister() { finder = new ElectronicBranchStudents(); } }
Here the StudentLister class is dependent on the interface StudentFinder and its implementation. We’d prefer if the class is just dependent on the interface alone but not the implementation class. But how can me make StudentLister class aware of the the implementation details of finder interface. We describe this scenario as the PLUGIN.
The aim is that the StudentLister class should not be linked to the finder implementation class at compile time, so that the implementation class can be changed at any time later based on the requirement.
Expanding this problem to the real world scenario, there will be many services and components. In each case we abstract these components through interfaces and access via interfaces. But if we wanna deploy these components in different ways then we should have plugin mechanism in place.
This is the place where set of all new light weight containers came in by implementing IoC design pattern.
There are three different ways of injecting the dependencies:
- Constructor Injection
- Injection through Setter Methods
- Interface Injection
Setter Injection via Spring framework
public class StudentLister { private StudentFinder finder; ApplicationContext context = new FileSystemXmlApplicationContext("src\\applicationconfig.xml"); public StudentLister() { //finder = new ElectronicsStudents(); // Get the instance using spring framework finder = (ElectronicsStudents)context.getBean("students"); } public static void main(String[] args) { new StudentLister(); } }
Here there is no compile time dependency on the finder interface implementation and hence can be plugged in into any implementation class at later point of time.
Here is the complete source code
https://github.com/ntallapa/ForumWorkspace/tree/master/Spring082201DI
Recent Comments