Spring Bean 定义继承

Bean 定义继承

Spring Bean 定义的继承与 Java 类的继承无关,但是继承的概念是一样的。你可以定义一个父 bean 的定义作为模板和其他子 bean 就可以从父 bean 中继承所需的配置。

当你使用基于 XML 的配置元数据时,通过使用父属性,指定父 bean 作为该属性的值来表明子 bean 的定义。

Bean 定义继承代码

  • Parent
public class Parent {

    private String message1;

    public Parent(){
        System.out.println("parent");
    }

    public String getMessage1() {
        return message1;
    }

    public void setMessage1(String message1) {
        this.message1 = message1;
    }
}

  • Son
public class Son {

    private String message1;
    private String message2;

    public Son(){
        super();
        System.out.println("son");
    }

    public String getMessage1() {
        return message1;
    }

    public void setMessage1(String message1) {
        this.message1 = message1;
    }

    public String getMessage2() {
        return message2;
    }

    public void setMessage2(String message2) {
        this.message2 = message2;
    }
}

  • 配置文件
<?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.xsd">


    <bean id="parent" class="com.cc.study.parent.Parent">
        <property name="message1" value="hello1"></property>
    </bean>

    <bean id="son" class="com.cc.study.parent.Son" parent="parent">
        <property name="message2" value="hello2"></property>
    </bean>
</beans>

  • 测试
  @Test
    public void demo(){
        String xmlPath = "parent.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        Son son = applicationContext.getBean("son",Son.class);
        System.out.println(son.getMessage1());
        System.out.println(son.getMessage2());
        System.out.println(Son.class.getSuperclass());
    }

在这里插入图片描述

可以看出在初始化Son的时候会先初始化Parent.并且Son可以获取到Parent的方法。但是Spring Bean 定义的继承与 Java 类的继承无关,所以通过查看Son.class.getSuperclass(),发现Son和Parent之间是没有Java的那种继承关系。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值