1、继承关系
bean-relation.xml
<?xml version="1.0" encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="address" class="com.spring.relation.Address"><property name="city" value="beijing^"></property><property name="location" value="los angles"></property></bean><bean id="address2" parent="address"><property name="location" value="new York"></property></bean> </beans>
Address.java
package com.spring.autowire;public class Address {private String city;private String location;public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}@Overridepublic String toString() {return "Address [city=" + city + ", location=" + location + "]";} }
测试
package com.spring.relation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-relation.xml");Address address = (Address)ctx.getBean("address");System.out.println(address);Address address2 = (Address)ctx.getBean("address2");System.out.println(address2);} }
【拓展】 abstract = true的时候,该bean是无法被实例化的。可以去掉用于实例化的class 属性,这样该bean仅为模板bean
<bean id="address" class="com.spring.relation.Address" abstract="true"><property name="city" value="beijing^"></property><property name="location" value="los angles"></property></bean><bean id="address2" parent="address"><property name="location" value="new York"></property></bean>