Java(Spring)学习笔记---->IOC容器中两个对象的关系

既然在传统的对象与对象中有继承,接口的关系,那么通过IOC容器创建的对象也有这样的关系,这篇文章笔者聊一聊IOC容器中的对象和抽象类

直接上代码,我们通过代码来聊聊。

首先先创建一个类

package com.kaifamiao.ioc.relation;

import java.util.logging.Logger;

/**
 * @author 后来的老李
 * @version 1.0
 */
public class Bear {
    
    //属性
    //无参构造
    //get和set
}

因为我们是通过IOC来研究,那么就是通过控制反转来创建对象,在通过依赖注入给对象注入属性的值。

注:不理解Spring的控制反转和依赖注入的读者可以看看笔者另一篇文章,里面有对Spring的控制反转和依赖注入的讲解,链接如下:

https://blog.csdn.net/xwe_147jyz/article/details/123771501?spm=1001.2014.3001.5502

切入正题,因此,我们给出XML文件:

<?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="father" class="com.kaifamiao.ioc.relation.Bear" abstract="true">
        <property name="type" value="兽类"/>
        <property name="familyName" value="熊"/>
    </bean>

    <bean id="child" class="com.kaifamiao.ioc.relation.Bear" parent="father">
        <property name="type" value="禽兽类"/>
        <property name="givenName" value="二"/>
    </bean>

</beans>

在上述的XML文件中,id=father的对象中,首先给出了Bear类包的路径,后面的abstract="true"说明了此类是抽象类,在注入属性的值。id=child的对象中,老样子给出了Bear类包的路径,后面的parent="father"说明了这个类继承了上面的father,之后在给属性注入值。

我们给出测试类:

package com.kaifamiao.ioc.relation;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author 后来的老李
 * @version 1.0
 */
public class RelationTest {

    public @Test void testInherit(){
        String configs="classpath*:com/**/relation/inherit.xml";
        AbstractApplicationContext context=new ClassPathXmlApplicationContext(configs);

        Bear b = context.getBean("child", Bear.class);
        Assert.assertNotNull(b);
        System.out.println(b.getType());
        System.out.println(b.getFamilyName());
        System.out.println(b.getGivenName());

        context.close();
    }
}

 我们在测试类中给出了输出child的对象的类型,姓氏,名字,因为child的继承了父类,所以有父类的所有属性,当然自己也可以给属性注入自己的值从而覆盖父类的属性值,这就是IOC中的继承。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值