IoC Container
There are two types of IoC containers.
- BeanFactory
- 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 programmingcode 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