In my previous blog we saw an overview of Spring IoC and DI.
Here we will see Dependency Injection (DI) in detail by answering following question:
- What is DI
- Ways of injecting Dependency using XML
- 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.
Ways of injecting Dependency
- Construction Injection
- Setter Injection
Construction Injection using XML
- We will see through an example how we can inject dependency using Constructor
- I have a class Car where I need Paint implementation
- I will inject Paint class inside Car
When we execute MainApp Spring reads xml file and prepares Paint and Car Bean for use.
<bean id="myPaint" class="com.main.spring.common.RedPaint"></bean>
In above line Spring create an Bean of RedPaint
<bean id="myCar" class="com.main.spring.constructorInj.Car"> <constructor-arg ref="myPaint" ></constructor-arg> </bean>
In above line Spring creates Bean of Car class and passed RedPaint Bean as an Constructor in Car class.
Vehicle veh = context.getBean("myCar", Vehicle.class);
Our bean is ready for work since all work was done by Container when we call veh.getType(); we get this output I will paint Red color
Setter Injection using XML
We will use same example as above with few changes
Only difference when compare to Constructor injection code is in the way Objects are injected
- We saw how to inject Bean using Constructor and Setter in XML
- You can get the code used above here. Just look for com.main.spring.setterInj and com.main.spring.constructorInj package.