Pages

Tuesday, July 27, 2010

Spring - Dependency Injection- Constructor Injection

As the name implies, using constructor the Spring IOC container will inject the dependencies. The constructor will take argument based on number of dependencies required. This is one of the drawback using Constructor based DI. You don't have option to reconfigure the dependencies at later point of time, since all the dependencies are resolved only at the time of invoking the constructor. if you don't have requirement to inject all the dependencies, please useSetter Injection technique to obtain the more flexibilty on configuring beans.
The below code is an example for how to pass dependency arguments to the constructor. Index attribute is useful when you have multiple arguments with the same type, you can inform the IOC container about the order of thearguments. You can pass bean reference using the ref element. 

Person.java 
 package com.spring; 
 public class Person { 
 private String name; 
 public Person(){
    System.out.println("Default Constructor >>>>>>>>> "); 
 }
public Person(String name) { 
    System.out.println(" Parameter Constructor >>>>>>>>> ");           
    this.name = name; 
 } 
 public String getName() { 
 return name; 
 } 
 public void setName(String name) {
 this.name = name; 
 } 
 } 

applicationContext.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="person"  class="com.spring.Person" >
    <constructor-arg value="John"></constructor-arg >
  </bean>
</beans>

Main.java 
package com.spring; 
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 
import org.springframework.core.io.Resource; 

 public class Main {
 /** * @param args */ 
 public static void main(String[] args) { 
 // TODO Auto-generated method stub 
 Resource resource = new ClassPathResource("applicationContext.xml"); 
 XmlBeanFactory beanFactory = new XmlBeanFactory(resource); 
 Person person = (Person) beanFactory.getBean("person"); 
 System.out.println(" Name >>> " + person.getName()); 
 } 
 }

Output 
=================== 
28 Jan, 2013 9:18:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 
INFO: Loading XML bean definitions from class path resource [applicationContext.xml] Parameter Constructor >>>>>>>>> 
 Name >>> John

No comments:

Post a Comment