Spring容器的继承

Spring中存在两种继承方式:
1.java继承机制
2.spring中的parent属性实现容器内部继承

一、创建两个pojo类(其中Student类继承Person类)

package cn.wk.scope;

public class Person {
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
package cn.wk.scope;

public class Student extends Person{
}

二、而后配置applicationContext.xml文件

1.利用java内部继承

<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-2.5.xsd">

    <bean id="person" class="cn.wk.scope.Person"></bean>

    <bean id="student" class="cn.wk.scope.Student">
        <!-- set注入 -->
        <property name="name" value="123"></property>
    </bean>
</beans>          

由于Studnent类继承于Person类,因此具有Person类中的所有属性(即name、age)。
但此种方法扩展性相对差一些,因为可以看到是在子类中赋值

2.利用spring容器提供的parent属性

<?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-2.5.xsd">

    <bean id="person" class="cn.wk.scope.Person">
        <!-- set注入 -->
        <property name="name" value="123"></property>
    </bean>
    <bean id="student" class="cn.wk.scope.Student" parent="person"></bean>
</beans>          

三、下面来利用junit测试一下

package cn.wk.scopeTest;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.wk.scope.Student;

public class StudentTest {

    @Test
    public void testStudent(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student=(Student)applicationContext.getBean("student");
        System.out.println(student.getName());
    }
}

结果可以自行测试。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值