Python 官方文档:入门教程 => 点击学习
spring配置文件parent与abstract 其实在基于spring框架开发的项目中,如果有多个bean都是一个类的实例,如配置多个数据源时,大部分配置的属性都一样,只有少部分
其实在基于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框架开发的项目中,如果有多个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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Spring配置文件中parent与abstract的使用
本文链接: https://www.lsjlt.com/news/130925.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0