Spring中父子关系的如何配置:
1)创建父类
public class Peson {
private String pname; // 字符串类型
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
2)创建子类
public class Student extends Peson {
public void say(){
System.out.println(this.getPname()+"继承关系!");
}
}
a)在bean中配置abstract属性为”true”,则spring容器不会为该类创建对象。
<!-- person object
abstract="true": 代表这个类是抽象类
-->
<bean id="peson" class="com.hlx.extend.Peson" abstract="true">
<property name="pname" value="加菲猫" />
</bean>
b).在bean中配置parent属性,则可以让该bean继承父类属性的值。
<!-- student object -->
<!-- 0) <bean id="student" class="com.hlx.extend.Student" /> -->
<bean id="student" parent="peson">
<property name="pname" value="fatter" />
</bean>
c)测试
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/hlx/extend/applicationContext.xml");
//抽象类不能实例化
Peson per = (Peson) context.getBean("student");
System.out.println(per.getPname());
输出:fatter
如果取消 0) test
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/hlx/extend/applicationContext.xml");
// 1 获得spring容器的person对象
Student stu = (Student) context.getBean("student");
//调用方法
stu.say();
则 fatter继承关系!
说明:子类重写父类!