Inversion of Control (IoC) & Dependency Injection

Inversion of Control (IoC)

Dependency Injection

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:-