Spring 框架Bean之间的关系(继承、依赖)
2016-08-18 15:13
330 查看
继承Bean的配置
Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父bean的bean称为子bean;子bean继承父bean的配置,包括父bean的属性配置;
子bean也可以覆盖从父bean中继承来的配置;
父bean可以作为配置模板,设置属性abstract=”true”,这样Spring将不会实例化该bean;
并不是父bean中的所有属性子bean都会继承,如abstract,autowire;
例子
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 抽象 bean:bean 的属性abstract为true,这样的 bean 不能被IOC实例化,只能用来被继承 若某一个bean的class没有指定,则该bean必须是一个抽象bean --> <bean id="address" p:city="Suzhou" p:street="Shilu" abstract="true"></bean> <!-- bean 配置的继承,使用 bean 的属性parent指定继承那个bean的配置 --> <bean id="address1" class="com.spring.test.autowire.Address" p:street="Shilu" parent="address"></bean> <!-- 依赖Bean配置 :前置依赖的Bean,会在本Bean实例化之前创建好,如果前置依赖于多个Bean,可以通过 4000 逗号,空格的方式配合Bean的名称 要求配置Person时,必须有一个关联的car,也就是person这个bean依赖于car这个bean --> <bean id="car" class="com.spring.test.Car" p:brand="Audi" p:price="200000"></bean> <bean id="person" class="com.spring.test.autowire.Person" p:address-ref="address1" depends-on="car"></bean> </beans>
Main.java
package com.spring.test.relation; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.test.autowire.Address; import com.spring.test.autowire.Person; public class Main { /** * 这里用到的java类可以在前两节中找到定义 */ @Test public void testCollections() { ApplicationContext context = new ClassPathXmlApplicationContext("beans-relation.xml"); Address address = (Address) context.getBean("address1"); System.out.println(address); Person person = (Person) context.getBean("person"); System.out.println(person); } }
相关文章推荐
- Spring 中 bean 之间的关系:继承;依赖
- Spring-4 bean之间的关系----继承和依赖
- spring bean之间的关系:继承;依赖
- spring学习小结3——bean之间的继承,依赖关系
- [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件
- spring bean之间的关系:继承;依赖
- spring- bean之间的关系 继承 依赖
- Spring配置--Bean之间的关系(继承和依赖)
- Spring4之Bean之间的关系(继承、依赖、引用)Bean的作用范围
- Spring学习记录(四)---bean之间的关系:继承、依赖
- 【跟我学spring 4.0 】之第五节-配置bean之间的关系:继承、依赖
- spring学习小结——bean之间的关系 继承 依赖
- (三)配置bean之间的关系:继承、依赖
- Spring4深入理解IOC&DI02----Bean配置--自动装配、bean之间的继承与依赖、使用外部属性文件
- Spring-5:Bean之间的继承与依赖
- 10009---bean 之间的关系:继承;依赖
- Spring内核研究-管理bean之间的关系二(自动依赖检查)
- Spring中bean之间的依赖关系depends-on
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- 一步一步学习Spring(3)-管理Bean之间的关系二(自动依赖检查)