Spring注入有继承关系的类(2)
编程技术  /  houtizong 发布于 3年前   82
被注入类的父类有相应的属性,Spring可以直接注入相应的属性,如下所例:
1.AClass类
package com.bijian.spring.test4;public class AClass { private String a; private String b; public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; }}
2.BClass类
package com.bijian.spring.test4;public class BClass extends AClass { String c; public String getC() { return c; } public void setC(String c) { this.c = c; } String fn() { return getA() + getB() + c; }}
3.AClass类对应的配置文件aclass4.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="bean1" class="com.bijian.spring.test4.AClass"> <property name="a"> <value>1</value> </property> <property name="b"> <value>2</value> </property> </bean></beans>
4.BClass类对应的配置文件bclass4.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="bean2" class="com.bijian.spring.test4.BClass"> <property name="a"> <value>5</value> </property> <property name="b"> <value>6</value> </property> <property name="c"> <value>3</value> </property> </bean></beans>
5.应用测试类Test.java
package com.bijian.spring.test4;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"bclass4.xml"}); //得到子类,结果是:563 BClass bclass = (BClass)ac.getBean("bean2"); String res = bclass.fn(); System.out.println(res); }}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接