Spring容器的继承
2016-01-14 11:26
681 查看
Spring中存在两种继承方式:
1.java继承机制
2.spring中的parent属性实现容器内部继承
一、创建两个pojo类(其中Student类继承Person类)
二、而后配置applicationContext.xml文件
1.利用java内部继承
由于Studnent类继承于Person类,因此具有Person类中的所有属性(即name、age)。
但此种方法扩展性相对差一些,因为可以看到是在子类中赋值
2.利用spring容器提供的parent属性
三、下面来利用junit测试一下
结果可以自行测试。
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()); } }
结果可以自行测试。
相关文章推荐
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- PostgreSQL教程(三):表的继承和分区表详解
- Lua面向对象之类和继承浅析
- 浅析Ruby中继承和消息的相关知识
- 设计引导--一个鸭子游戏引发的设计理念(多态,继承,抽象,接口,策略者模式)
- C++实现不能被继承的类实例分析
- PHP类的封装与继承详解
- js继承 Base类的源码解析
- Javascript 面向对象 继承
- JavaScript 继承使用分析
- Javascript面向对象编程(二) 构造函数的继承
- javascript面向对象之Javascript 继承
- JavaScript 对象、函数和继承
- 学习javascript面向对象 javascript实现继承的方式
- 关于JavaScript的面向对象和继承有利新手学习
- JavaScript 继承详解(一)
- JavaScript 继承详解(二)
- javascript继承的六大模式小结