证明如下:

思路定义两个实体类每个实体类的成员变量(字段)名和setter 和getter的名字都不一样:

原因是:bean的声明周期的原因:有一步是:注入属性。

其中一个类引用了另一个类。

被引用类的Address的代码如下:

 package com.timo.domain;

 public class Address {
private String city6;
private String state3; public String getCity4() {
return city6;
} public void setCity(String city) {
this.city6 = city;
} public String getState2() {
return state3;
} public void setState(String state) {
this.state3 = state;
}
}

引用类Student的代码如下:

 package com.timo.domain;

 public class Student {
private Integer age;
private String name;
private Address address; public Integer getAge2() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getName2() {
return name;
} public void setName(String name) {
this.name = name;
} public Address getAddress() {
return address;
} public void setAddress(Address address) {
this.address = address;
} @Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
", address=" + address +
'}';
}
}

配置文件.xml的代码如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.timo.domain.Address">
<!-- collaborators and configuration for this bean go here -->
<property name="city" value="合肥市"/>
<property name="state" value="安徽省"/>
</bean> <bean id="student" class="com.timo.domain.Student">
<!-- collaborators and configuration for this bean go here -->
<property name="address" ref="address"/>
<property name="age" value=""/>
<property name="name" value="欧阳凤"/>
</bean> <!-- more bean definitions go here --> </beans>

测试类Test的代码如下:

package com.timo.test;

import com.timo.domain.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
String city = applicationContext.getBean(Student.class).getAddress().getCity4();
System.out.println("she inhabit in :"+city);
}
}
04-26 01:19