Person
package com.spring.extend; public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
student
package com.spring.extend; public class Student extends Person { }
ApplicationContext.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-2.5.xsd"> <!--在父类中进行赋值,子类通过 parent属性继承父类的内容 --> <bean id="person" class="com.spring.extend.Person"> <property name="name" value="aaa"></property> </bean> <!-- parent 实现了Spring容器内部的继承关系 --> <bean id="student" class="com.spring.extend.Student" parent="person"></bean> <!-- 因为java的继承机制,子类继承的父类的setXX方法,左右子类可以利用setXXX方法注入值 --> <bean id="person2" class="com.spring.extend.Person"></bean> <bean id="student2" class="com.spring.extend.Student"> <property name="name" value="bbb"></property> </bean> </beans>
测试
package com.spring.extend.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.extend.Student; public class ExtendsTest { @Test public void testDI_XML_constructor(){ ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); // Student student=(Student) context.getBean("student"); // // System.out.println(student.getName()); //aaa // Student student=(Student) context.getBean("student2"); // // System.out.println(student.getName()); //bbb } }
时间: 2024-10-06 21:55:38