Spring IOC注入(四)继承

继承:并不是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对象的生命周期~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值