就像構(gòu)造函數(shù)注入一樣,我們可以使用setter注入另一個bean的依賴項(xiàng)。在這種情況下,我們使用
property
元素。在這里,我們的場景是
Employee HAS-A Address
。 Address類對象將稱為從屬對象。首先讓我們看一下Address類:
Address.java
該類包含四個屬性,即setter和getter以及toString()方法。
package com.nhooo;
public class Address {
private String addressLine1,city,state,country;
//getters and setters
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
Employee.java
它包含三個屬性id,名稱和地址(依賴對象),使用displayInfo()方法的setter和getter。
package com.nhooo; 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
屬性
元素的
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="com.nhooo.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="com.nhooo.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并調(diào)用displayInfo()方法。
package com.nhooo; 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(); } }