如果類之間存在HAS-A關(guān)系,則首先創(chuàng)建依賴對象(包含對象)的實(shí)例,然后將其作為主類構(gòu)造函數(shù)的參數(shù)傳遞。在這里,我們的場景是員工HAS-A地址。 Address類對象將稱為從屬對象。首先讓我們看一下Address類:
Address.java
該類包含三個屬性,一個構(gòu)造函數(shù)和toString()方法以返回這些對象的值。
package com.nhooo;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return city+" "+state+" "+country;
}
}
Employee.java
它包含三個屬性id,名稱和地址(從屬對象),兩個構(gòu)造函數(shù)和show()方法來顯示當(dāng)前對象(包括依賴對象)的記錄。
package com.nhooo;
public class Employee {
private int id;
private String name;
private Address address;//Aggregation
public Employee() {System.out.println("def cons");}
public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
applicationContext.xml
ref 屬性用于定義另一個對象的引用,例如,我們將依賴對象傳遞為構(gòu)造函數(shù)參數(shù)。
<?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="a1" class="com.nhooo.Address"> <constructor-arg value="ghaziabad"></constructor-arg> <constructor-arg value="UP"></constructor-arg> <constructor-arg value="India"></constructor-arg> </bean> <bean id="e" class="com.nhooo.Employee"> <constructor-arg value="12" type="int"></constructor-arg> <constructor-arg value="Sonoo"></constructor-arg> <constructor-arg> <ref bean="a1"/> </constructor-arg> </bean> </beans>
Test.java
此類從applicationContext.xml文件獲取Bean并調(diào)用show方法。
package com.nhooo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}