Thursday 19 January 2017

IOC container Dependency Injection in Spring

By,
Santosh

The Inversion of Control (IoC) container is responsible to assemble, instantiate and configure the objects of classes. The Inversion of Control (IoC) container take information’s from XML file and works respectively. The main tasks performed by Inversion of Control (IoC) container are:
o instantiate the class.
o configure object.
o assemble the dependencies.

Two types of Inversion of Control (IoC) containers. That are as follows:
1.  org.springframework.beans.factory.BeanFactory and org.springframework.context.ApplicationContext interfaces works as the Inversion of Control (IoC) container. The ApplicationContext interface is create on the top of the BeanFactory interface. It has some additional functionality than BeanFactory like application layer specific context, event propagation, message resource handling, simple integration with Spring's AOP, for web application. So this interface is better to use than BeanFactory.
2. BeanFactory
3. ApplicationContext
Using BeanFactory
The BeanFactory interface is implemented by the XmlBeanFactory class. To work with the BeanFactory, we have to create the object of XmlBeanFactory class as below:
Resource res=new ClassPathResource("applicationContext.xml"); 
BeanFactory fact=new XmlBeanFactory(res); 

Using ApplicationContext
ApplicationContext interface implemented class is the ClassPathXmlApplicationContext. We have to instantiate the ClassPathXmlApplicationContext class to work the ApplicationContext as given below:
ApplicationContext context =    new ClassPathXmlApplicationContext("applicationContext.xml"); 
Constructor of ClassPathXmlApplicationContext class receives string, so we have to pass the name of the xml file to create the instance of ApplicationContext interface.

Dependency Injection:-
For making programming code loosely coupled Dependency Injection is helpful. To understand the Dependency Injection better, first understand the Dependency Lookup:
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource.
Example ex = new AImpl(); 

In such cases, we get the resource directly by new keyword. Another way is factory method.
Example ex = A.getA(); 
This case, we get the resource by calling the static factory method getA().
and, we can get the resource by Java Naming Directory Interface as:
Context context = new InitialContext(); 
Context environmentCtx = (Context) ctx.lookup("java:comp/env"); 
Example object = (Example)environmentCtx.lookup("Example"); 
Problems of Dependency Lookup

Mainly two problems of DL.
o dependency lookup approach makes the tight coupling for code. If resource is changed, we have to perform modification in the code.
o Not easy for testing This approach creates problems while testing.

No comments:

Post a Comment