Inversion of Control (IoC) & Dependency Injection

Inversion of Control (IoC)

Inversion of control is a common characteristic of frameworks. As the name suggests it inverts something. So, What aspect of control it is inverting?

Dependency Injection

The basic idea of the Dependency Injection is to have a separate object, an assembler, that populates a field in a specific class with an appropriate implementation for the particular interface.

public MovieLister(MovieFinder finder) {
this.finder = finder;
}
public ColonMovieFinder(String filename) {
this.filename = filename;
}
private MutablePicoContainer configureContainer() {
MutablePicoContainer pico = new DefaultPicoContainer();
Parameter[] finderParams = {new ConstantParameter("movies1.txt")};
pico.registerComponentImplementation(MovieFinder.class, ColonMovieFinder.class, finderParams);
pico.registerComponentImplementation(MovieLister.class);
return pico;
}
public void testWithPico() {
MutablePicoContainer pico = configureContainer();
MovieLister lister = (MovieLister) pico.getComponentInstance(MovieLister.class);
Movie[] movies = lister.moviesDirectedBy("S. S. Rajamouli");
assertEquals("Bahubali", movies[0].getTitle());
}
private MovieFinder finder;
public void setFinder(MovieFinder finder) {
this.finder = finder;
}
public void setFilename(String filename) {
this.filename = filename;
}
<beans>
<bean id="MovieLister" class="spring.MovieLister">
<property name="finder">
<ref local="MovieFinder"/>
</property>
</bean>
<bean id="MovieFinder" class="spring.ColonMovieFinder">
<property name="filename">
<value>movies1.txt</value>
</property>
</bean>
</beans>
public void testWithSpring() throws Exception {
ApplicationContext ctx = new FileSystemXmlApplicationContext("spring.xml");
MovieLister lister = (MovieLister) ctx.getBean("MovieLister");
Movie[] movies = lister.moviesDirectedBy("S. S. Rajamouli");
assertEquals("Bahubali", movies[0].getTitle());
}

Conclusion:-

So, basically IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source. Where as Dependency Injection means that this is done without the object intervention, usually by a framework component that passes constructor parameter and set properties.