In last post I explained what is dependency injection (DI). Now I will focus on how the concept is implemented in Spring framework. If we are clear on the concept of DI, remaining is piece of cake.
There are 2 ways to implement DI in Spring
1. Using annotations
Spring is basically annotation driven language (see here). @Autowired is the annotation which will help us inject dependencies in Spring. @Autowired will tell the code to look for given object somewhere in code. The dependency injection can be implemented in 3 ways
a. Using my previous Employee- Address example for dependency injection, adding address dependency through constructor
Class Employee
{
public Address address;
public String name;//other stuff
@Autowired
Employee(Address address)
{
this.address=address
}}
And In application context xml add
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="EmployeeBean" class="com.test.Employee"> <property name="name" value="kamal" /> </bean> <bean id="AddressBean" class="com.test.Address"> <property name="street" value="43rd" /> <property name="apt" value="29" /> <property name="city" value="New york" /> </bean>
b. using Setter- similar to constructor
Class Employee
{
public Address address;
public String name;//other stuff
Employee()
{
}@Autowired
public void setAddress(Address address)
{
this.address=address;
}}
c. Using Field
Class Employee
{
@Autowired
public Address address;public String name;//other stuff
Employee()
{
}}
2. Using XML configuration (application context)
Same as above (almost), we will not use @Autowired but add the dependency in the xml itself
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="EmployeeBean" class="com.test.Employee"> <property name="name" value="kamal" /> <property name="address" ref="AddressBean" /> </bean> <bean id="AddressBean" class="com.test.Address"> <property name="street" value="43rd" /> <property name="apt" value="29" /> <property name="city" value="New york" /> </bean>
Finally to run your example add these lines to code
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {“SpringBeans.xml”});Customer cust = (Customer)context.getBean(“EmployeeBean”);
Further References
http://www.vogella.com/articles/SpringDependencyInjection/article.html
http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/