Thursday, September 3, 2015

IoC Container

IoC Container

There are two types of IoC containers. 
  1. BeanFactory
  2. ApplicationContext
  • to instantiate the application class
  • to configure the object
  • to assemble the dependencies between the objects

BeanFactory and the ApplicationContext

The org.springframework.beans.factory.BeanFactory org.springframework.context.ApplicationContext interfaces acts as the IoC container.

The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory

Resource resource=new ClassPathResource("applicationContext.xml");  
BeanFactory factory=new XmlBeanFactory(resource);  

Using ApplicationContext

ApplicationContext context =   
    new ClassPathXmlApplicationContext("applicationContext.xml");

Dependency Injection in Spring

Dependency Injection (DI) is a design pattern that removes the dependency from the programming
code so that it can be easy to manage and test the application. Dependency Injection makes our
programming code loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first:

Dependency Lookup
A obj = new AImpl();
A obj = A.getA();

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");

Problems of Dependency Lookup

  • tight coupling
  • Not easy for testing

Dependency Injection

Spring framework provides two ways to inject dependency
  • By Constructor
  • By Setter method

Examples



Spring Framework Introduction


Spring

developed by Rod Johnson in 2003

Advantages of Spring Framework


  1. Predefined Templates
  2. Loose Coupling
  3. Easy to test
  4. Lightweight
  5. Fast Development
  6. Powerful abstraction
  7. Declarative support

Modules

  1. Core Beans Context
  2. Expression Language
  3. AOP, Aspects and Instrumentation
  4. Data Access / Integration
  5. JDBC, ORM, OXM, JMS and Transaction modules.
  6. Web, Web-Servlet, Web-Struts and Web-Portlet.