Spring中存在两种继承方式:
1.java继承机制
2.spring中的parent属性实现容器内部继承
一、创建两个pojo类(其中Student类继承Person类)
package cn.wk.scope;
public class Person {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
package cn.wk.scope;
public class Student extends Person{
}
二、而后配置applicationContext.xml文件
1.利用java内部继承
<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-2.5.xsd">
<bean id="person" class="cn.wk.scope.Person"></bean>
<bean id="student" class="cn.wk.scope.Student">
<!-- set注入 -->
<property name="name" value="123"></property>
</bean>
</beans>
由于Studnent类继承于Person类,因此具有Person类中的所有属性(即name、age)。
但此种方法扩展性相对差一些,因为可以看到是在子类中赋值
2.利用spring容器提供的parent属性
<?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-2.5.xsd">
<bean id="person" class="cn.wk.scope.Person">
<!-- set注入 -->
<property name="name" value="123"></property>
</bean>
<bean id="student" class="cn.wk.scope.Student" parent="person"></bean>
</beans>
三、下面来利用junit测试一下
package cn.wk.scopeTest;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.wk.scope.Student;
public class StudentTest {
@Test
public void testStudent(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
Student student=(Student)applicationContext.getBean("student");
System.out.println(student.getName());
}
}
结果可以自行测试。