既然在传统的对象与对象中有继承,接口的关系,那么通过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中的继承。