被注入类的父类有相应的属性,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);
}
}