使用Setter方法进行依赖注入的示例

与构造函数注入类似,我们可以使用setter方法注入另一个bean的依赖项。在这种情况下,我们使用property元素。在这里,我们的场景是Employee拥有一个Address。Address类对象将被称为依赖对象。让我们首先看一下Address类:

Address.java
这个类包含四个属性,setter和getter方法以及toString()方法。

package cn.javatiku;  
  
public class Address {  
private String addressLine1,city,state,country;  
  
//getters and setters  
  
public String toString(){  
    return addressLine1+" "+city+" "+state+" "+country;  
}  

Employee.java

它包含三个属性id,name和address(依赖对象),setter和getter方法以及displayInfo()方法。

package cn.javatiku;  
  
public class Employee {  
private int id;  
private String name;  
private Address address;  
  
//setters and getters  
  
void displayInfo(){  
    System.out.println(id+" "+name);  
    System.out.println(address);  
}  
}  

applicationContext.xml

property元素的ref属性用于定义另一个bean的引用。

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  
<bean id="address1" class="cn.javatiku.Address">  
<property name="addressLine1" value="51,Lohianagar"></property>  
<property name="city" value="Ghaziabad"></property>  
<property name="state" value="UP"></property>  
<property name="country" value="India"></property>  
</bean>  
  
<bean id="obj" class="cn.javatiku.Employee">  
<property name="id" value="1"></property>  
<property name="name" value="Sachin Yadav"></property>  
<property name="address" ref="address1"></property>  
</bean>  
  
</beans>  

Test.java

该类从applicationContext.xml文件中获取bean,并调用displayInfo()方法。

package cn.javatiku;  
  
import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
  
public class Test {  
public static void main(String[] args) {  
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    Employee e=(Employee)factory.getBean("obj");  
    e.displayInfo();  
      
}  
} 

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想