Spring中applicationContex的parent属性

作用

比如有一个animal类,有字段name、legs,想通过animal类创建多个4条腿的动物实例,每个动物的名字不一样,此时我们可以parent字段,通过一个Animal类创建多个实例。

实现
//Animal类
public class Animal {
    private int legs;
    private String name;

    @Override
    public String toString() {
        return "Animal{" +
                "legs=" + legs +
                ", name='" + name + '\'' +
                '}';
    }

    public int getLegs() {
        return legs;
    }

    public void setLegs(int legs) {
        this.legs = legs;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="animal" class="com.chen.Animal" abstract="true">
        <property name="legs" value="4"/>
    </bean>
    <bean id="animal1"  parent="animal">
        <property name="name" value="monkey"/>
    </bean>
    <bean id="animal2"  parent="animal">
        <property name="name" value="cat"/>
    </bean>
</beans>
//运行类
public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Animal animal1 = context.getBean("animal1", Animal.class);
        System.out.println(animal1);
        Animal animal2 = context.getBean("animal2", Animal.class);
        System.out.println(animal2);

    }

输出
在这里插入图片描述

说明

当我们需要创建的对象有很多通用的属性,比如上例中的leg都等于4,那么我只需要在parent的bean定义一个leg等于4,在每个实例的bean中只需要定义name即可,得到的对象自然就包含leg等于4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值