Bean之间的关系主要有两种:继承和依赖。
1.继承:bean可以通过parent继承其他bean,同时可以使用abstract定义一个抽象bean,抽象bean不能被实例化,用于被继承。
这里有两个类,Person和Address
Java文件代码:
package com.study.beanRelation;
public class Person {
private String name;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address +"]";
}
}
package com.study.beanRelation;
public class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
}
xml文件代码:
<!--使用abstract定义抽象bean,抽象bean不能被实例化,用于被继承 -->
<bean id="address" p:city="hefei"
abstract="true"></bean>
<bean id="address1" class="com.study.beanRelation.Address" p:city="hefei"
p:street="hezuohualu" parent="address"></bean>
<!--使用parent继承bean -->
<bean id="address2" parent="address1"
p:street="jinzhai"></bean>
上述代码中id为address的bean为抽象bean,被address1继承,抽象bean可以不指定类型,但继承的子bean必须指定。
address1和address2中只有street的值不同,因此address2继承address1简化了配置文件。
2.依赖。使用depend-on定义bean之间的依赖关系,需要注意的是被依赖的bean必须要先初始化,否则报错。
xml文件代码:
<!--bean之间的依赖关系-->
<bean id="person" class="com.study.beanRelation.Person"
p:name="zhangshiwei" depends-on="address2" p:address-ref="address2"></bean>