摘要:属性参考至对象。一个对象的属性参考另一个对象的实例,如,学生(StudentBean)对象有两个属性一个是name一个是addressBean,name是一个String型,而addressBean是AddressBean对象(地址对象)的一个实例。
●
StrudentBean.java
package com.kela.spring.ioc;
public class StudentBean {
private String name;
private AddressBean addressBean;
public AddressBean getAddressBean() {
return addressBean;
}
public void setAddressBean(AddressBean addressBean) {
this.addressBean = addressBean;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
●
AddressBean.java
package com.kela.spring.ioc;
public class AddressBean {
private String addressName;
public String getAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
}
●
beans-config_2.xml
<?xml
version=
"1.0"
encoding=
"GB2312"
?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
<beans>
<bean
id=
"addressBean"
class=
"com.kela.spring.ioc.AddressBean"
>
<property
name=
"addressName"
>
<value>
团结大街向阳路
123
号
</value>
</property>
</bean>
<bean
id=
"studentBean"
class=
"com.kela.spring.ioc.StudentBean"
>
<property
name=
"name"
>
<value>
KangFeng
</value>
</property>
<property
name=
"addressBean"
>
<!--
注意这里已不是
value
了,改为
ref
-->
<ref
bean=
"addressBean"
></ref>
</property>
</bean>
</beans>
●
TestClass.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestClass {
public void method_2() {
try {
ApplicationContext context = new FileSystemXmlApplicationContext("bin\\com\\kela\\spring\\ioc\\beans-config_2.xml");
StudentBean studentBean = (StudentBean)context.getBean("studentBean");
System.out.println("
姓名:" + studentBean.getName() + ";地址:" + studentBean.getAddressBean().getAddressName());
} catch (Exception e) {
System.out.println("[ERROR]" + e.getMessage());
}
}
public static void main(String[] args) {
TestClass testClass = new TestClass();
testClass.method_2();
}
}
●
学习小结
“Don’t Call Me,I‘ll Call You”。