Spring配置文件parent与abstract
其实在基于spring框架开发的项目中,如果有多个bean都是一个类的实例,如配置多个数据源时,大部分配置的属性都一样,只有少部分不一样。
这样的话在配置文件中可以配置和对象一样进行继承。
例如
<bean id="testParent" abstract="true" class="com.bean.TestBean">
<property name="param1" value="父参数1"/>
<property name="param2" value="父参数2"/>
</bean>
<bean id="testBeanChild1" parent="testParent"/>
<bean id="testBeanChild2" parent="testParent">
<property name="param1" value="子参数1"/>
</bean>
其中 abstract=”true” 的配置表示:此类在Spring容器中不会生成实例。
parent=”testBeanParent” 代表子类继承了testBeanParent,会生成具体实例,在子类Bean中配置会覆盖父类对应的属性。
spring使用parent属性来减少配置
在基于spring框架开发的项目中,如果有多个bean都是一个类的实力,如配置多个数据源时,大部分配置的属性都一样,只有少部分不一样,经常是copy上一个的定义,然后修改不一样的地方。其实spring bean定义也可以和对象一样进行继承。
示例如下:
<bean id="testBeanParent" abstract="true" class="com.wanzheng90.bean.TestBean">
<property name="param1" value="父参数1"/>
<property name="param2" value="父参数2"/>
</bean>
<bean id="testBeanChild1" parent="testBeanParent"/>
<bean id="testBeanChild2" parent="testBeanParent">
<property name="param1" value="子参数1"/>
</bean>
testBeanParent是父bean,其中abstract=“true”表示testBeanParen不会被创建,类似于于抽象类。其中testBeanChild1、testBeanChild2继承了testBeanParent、,其中testBeanChild2重新对param1属性进行了配置,因此会覆盖testBeanParent
对param1属性属性的配置。
代码如下:
TestBean
public class TestBean {
private String param1;
private String param2;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
}
App:
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
TestBean testBeanChild1 = (TestBean) context.getBean("testBeanChild1");
System.out.println( testBeanChild1.getParam1());
System.out.println( testBeanChild1.getParam2());
TestBean testBeanChild2 = (TestBean) context.getBean("testBeanChild2");
System.out.println( testBeanChild2.getParam1());
System.out.println( testBeanChild2.getParam2());
}
}
app main函数输出:
父参数1
父参数2
子参数1
父参数2
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)