本文共 4460 字,大约阅读时间需要 14 分钟。
通常,JavaBean 的属性是私有的,同时拥有一组存取器方法,以setXXX() 和getXXX() 形式存在。Spring 可以借助属性的set方法来配置属性的值,以实现setter方式的注入。
package com.sjf.bean;
/**
* 学生实体类
* @author sjf0115
*
*/
public class Student {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("个人详细信息如下:" + "\n");
stringBuilder.append("name:" + name + "\n");
stringBuilder.append("age:" + age);
return stringBuilder.toString();
}
}
<bean id = "yoona" class = "com.sjf.bean.Student">
<property name="name" value = "yoona"/>
<property name="age" value = "24" />
</bean>
public class School {
private String name;
public void setName(String name) {
this.name = name;
}
}
private String name;
private int age;
private School school;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSchool(School school) {
this.school = school;
}
<bean id = "xidian" class = "com.sjf.bean.School">
<property name = "name" value = "西电"/>
</bean>
<bean id = "yoona" class = "com.sjf.bean.Student">
<property name="name" value = "yoona"/>
<property name="age" value = "24" />
<property name="school" ref="xidian"></property>
</bean>
<bean id = "xidian" class = "com.sjf.bean.School">
<property name = "name" value = "西电"/>
</bean>
<bean id = "yoona" class = "com.sjf.bean.Student">
<property name="name" value = "yoona"/>
<property name="age" value = "24" />
<property name="school" ref="xidian"></property>
</bean>
<bean id = "xiaosi" class = "com.sjf.bean.Student">
<property name="name" value = "xiaosi"/>
<property name="age" value = "21" />
<property name="school" ref="xidian"></property>
</bean>
<bean id = "xidian" class = "com.sjf.bean.School">
<property name = "name" value = "西电"/>
</bean>
package com.sjf.bean;
public class Hobby {
private String desc;
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return desc;
}
}
package com.sjf.bean;
/**
* 学生实体类
* @author sjf0115
*
*/
public class Student {
private String name;
private int age;
private Hobby hobby;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setHobby(Hobby hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("个人详细信息如下:" + "\n");
stringBuilder.append("name:" + name + "\n");
stringBuilder.append("age:" + age + "\n");
stringBuilder.append("hobby:" + hobby.toString());
return stringBuilder.toString();
}
}
<bean id = "yoona" class = "com.sjf.bean.Student">
<property name="name" value = "xiaosi"/>
<property name="age" value = "21" />
<property name="hobby">
<bean class = "com.sjf.bean.Hobby">
<property name="desc" value = "喜欢踢足球,打羽毛球"/>
</bean>
</property>
</bean>