iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring配置文件中parent与abstract的使用
  • 421
分享到

Spring配置文件中parent与abstract的使用

2024-04-02 19:04:59 421人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

spring配置文件parent与abstract 其实在基于spring框架开发的项目中,如果有多个bean都是一个类的实例,如配置多个数据源时,大部分配置的属性都一样,只有少部分

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Spring配置文件中parent与abstract的使用

本文链接: https://www.lsjlt.com/news/130925.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作