您的位置:首页 > 编程语言 > Java开发

Spring IOC注入(四)继承

2016-07-16 14:58 375 查看
继承:并不是OO的继承关系~只是bean的定义的继承,指bean的配置可去继承~

要怎么做才能让bean之间继承呢~

父类:

true 抽象化 代码中不能getBean获取其对象

abstract =

false 默认

子类:

parent = "父类bean的id/name"

写个例子来更好的理解下~

代码如下:

POJO类就不写了~有需要的可以看我上一篇文章:Spring IOC注入(三)自动注入

那我现在写一下配置文件extends.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 
<bean name="t1" class="com.x.spring.bean.Student" abstract="true">
<property name="id" value="99999"></property>
</bean>
<bean name="t2" class="com.x.spring.bean.Student" parent="t1">

</bean>

</beans>




abstract="true" 表示当前的配置是一个抽象的配置,

这时候我们在代码中就不能通过这个bean的名字teacher来获得相应的对象了(和java中的抽象类不能直接new对象的道理一样)

但是我们可以在写一个配置去继承这个抽象的配置,当然即使当前这个配置不是抽象的,也能够被继承(和java中继承一样)

parent="t1" 表示当前配置是继承了另外一个名字叫t1的bean的配置,配置和配置的继承像java中的类和类直接的继承一样,子类会把父类中的对象继承过来.当然在子配置里面依然是可以覆盖父配置中已经写的配置信息.

测试类ExtendTest:

public class ExtendTest {

public static void main(String[] args) {
String[] path = {"extends.xml"};
ApplicationContext container =
new ClassPathXmlApplicationContext(path);
Student s2 = (Student)container.getBean("t2");
System.out.println(s2.getId());
}
}


效果图:



其实这个继承还是蛮简单的~

这个就写到这里了~

下一篇写bean对象的生命周期~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOC继承 bean oo ioc spring