一个bean可以包含很多个配置信息,例如构造器参数,属性值,和特定容器的信息(如:初始化方法、静态工厂名称)等等。
一个child bean的定义可以从parent bean中继承配置数据。child bean可以根据需要覆盖一些属性值,或添加其他新的属性。
Spring bean的继承定义和Java class的继承没有关系,但是继承的原理是相似的。你可以定义一个parent bean作为模板,让其他的child bean来继承它的必需参数配置。
Bean的模板定义:
实际环境中你可以定义一个模板bean来供其他的child bean继承,这样可以省去很多工作。当定义一个模板bean的时候,你可以不用指定class属性,当时需要指定abstract属性值为true,就像下面:
<?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-3.0.xsd">
<bean id="beanTeamplate" abstract="true">
<property name="message1" value="Hello World!"/>
<property name="message2" value="Hello Second World!"/>
<property name="message3" value="Namaste India!"/>
</bean>
<bean id="helloIndia" class="com.tutorialspoint.HelloIndia" parent="beanTeamplate">
<property name="message1" value="Hello India!"/>
<property name="message3" value="Namaste India!"/>
</bean>
</beans>
由于parent bean中没有指定class属性,所以这个bean是不能被实例化的,因此它被明确的标记为abstract。当一个bean被定义成这样的模板bean,那它只能作为被其他child bean继承的模板bean。
一个child bean的定义可以从parent bean中继承配置数据。child bean可以根据需要覆盖一些属性值,或添加其他新的属性。
Spring bean的继承定义和Java class的继承没有关系,但是继承的原理是相似的。你可以定义一个parent bean作为模板,让其他的child bean来继承它的必需参数配置。
Bean的模板定义:
实际环境中你可以定义一个模板bean来供其他的child bean继承,这样可以省去很多工作。当定义一个模板bean的时候,你可以不用指定class属性,当时需要指定abstract属性值为true,就像下面:
<?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-3.0.xsd">
<bean id="beanTeamplate" abstract="true">
<property name="message1" value="Hello World!"/>
<property name="message2" value="Hello Second World!"/>
<property name="message3" value="Namaste India!"/>
</bean>
<bean id="helloIndia" class="com.tutorialspoint.HelloIndia" parent="beanTeamplate">
<property name="message1" value="Hello India!"/>
<property name="message3" value="Namaste India!"/>
</bean>
</beans>
由于parent bean中没有指定class属性,所以这个bean是不能被实例化的,因此它被明确的标记为abstract。当一个bean被定义成这样的模板bean,那它只能作为被其他child bean继承的模板bean。