您的位置:首页 > 编程语言 > Java开发

Spring 中 bean 之间的关系:继承;依赖

2016-06-11 23:06 549 查看
bean的配置

beans_relation.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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 
<!-- bean  address 是一个抽象bean,其只能被继承,不能被实例化,即其是一个模版bean -->
<bean id="address" abstract="true">
<property name="city" value="ShangHai"></property>
<property name="street" value="SuZhouRoad"></property>
</bean>

<bean id="address1" class="com.baidu.autowire.Address">
<property name="city" value="ShangHai"></property>
<property name="street" value="NanJingRoad"></property>
</bean>

<!-- bean 之间的关系:继承、依赖
Spring 允许继承 bean 的配置, 被继承的 bean 称为父 bean. 继承这个父 Bean 的 Bean 称为子 Bean。
①. 子 Bean 从父 Bean 中继承配置, 包括 Bean 的属性配置,
②. 子 Bean 也可以覆盖从父 Bean 继承过来的配置,
③. 父 Bean 可以作为配置模板, 也可以作为 Bean 实例.
若只想把父 Bean 作为模板, 可以设置 <bean> 的abstract 属性为true,
这样 Spring 将不会实例化这个 Bean
④. 并不是 <bean> 元素里的所有属性都会被继承. 比如: autowire, abstract 等.
⑤. 也可以忽略父 Bean 的 class 属性, 让子 Bean 指定自己的类, 而共享相同的属性配置.
但此时 abstract 必须设为 true:即,若某一个bean 的class 属性没有指定,则该bean 必须是一个抽象bean

配置bean 的继承 :使用bean 的parent 属性指定继承哪个bean 的配置 -->
<bean id="address2"  parent="address1">
<property name="street" value="GuangZhouRoad"></property>
</bean>

<bean id="phone" class="com.baidu.autowire.Phone" p:brand="HuaWei" p:price="4899"/>

<!-- 要求在配置Person 时,必须有一个关联的Phone! 即:person 这个bean 依赖于Phone 这个bean,如果没有Phone,person 就不能实例化,
就会报错(org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'phone' is defined) -->
<bean id="person" class="com.baidu.autowire.Person" p:name="Jim" p:age="25"
p:address-ref="address2" depends-on="phone"></bean>

</beans>


测试方法:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.baidu.autowire.Address;
import com.baidu.autowire.Person;

public class TestSpringRelation {

public static void main(String[] args) {

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans_relation.xml");

Address address1 = (Address) applicationContext.getBean("address1");
System.out.println(address1);

Address address2 = (Address) applicationContext.getBean("address2");
System.out.println(address2);

Person person = (Person) applicationContext.getBean("person");
System.out.println(person);

}
}


运行结果:

Address [city=ShangHai, street=NanJingRoad]
Address [city=ShangHai, street=GuangZhouRoad]
Person [name=Jim, age=25, phone=null, address=Address [city=ShangHai, street=GuangZhouRoad]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: