Bean 之间的关系:继承、依赖。

Bean 继承:

  • Spring 允许继承 bean 的配置 , 被继承的 bean 称为父 bean , 继承这个父 bean 的 bean 称为子 bean。
  • 子 bean 从父 bean 中继承配置 , 包括 bean 的属性配置。
  • 子 bean 也可以覆盖从父 bean 继承过来的配置。
  • 父 bean 可以作为配置模板 , 也可以作为 bean 实例。若只想把父 bean 作为模板 , 可以设置 <bean> 的 abstract 属性为 true , 这样 IOC容器将不会实例这个 bean。
  • 并不是 <bean> 元素里的所有属性都会被继承。比如: autowire , abstract 等。
  • 父 bean 的 class 属性可以忽略 , 让子 bean 指定自己的类 , 而共享相同的属性配置。但此时 abstract 必须设为 true。
 <?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 id="address" class="com.itdoc.spring.extendsinfo.Address" p:city="DaLian" p:street="ShaHeKou"/> <bean id="address1" class="com.itdoc.spring.extendsinfo.Address" p:street="GanJingZi" parent="address"/> </beans>
 package com.itdoc.spring.extendsinfo;

 /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:48
*/
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 + '\'' +
'}';
}
}
 package com.itdoc.spring.extendsinfo;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:55
*/
public class Main { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("beans_extends.xml");
Address address = (Address) app.getBean("address");
System.out.println(address); System.out.println("-------------------");
address = (Address) app.getBean("address1");
System.out.println(address); }
}

控制台输出:

Address{city='DaLian', street='ShaHeKou'}
-------------------
Address{city='DaLian', street='GanJingZi'}

 <?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 id="address" class="com.itdoc.spring.extendsinfo.Address" p:city="DaLian" p:street="ShaHeKou" abstract="true"/> <bean id="address1" class="com.itdoc.spring.extendsinfo.Address" p:street="GanJingZi" parent="address"/> </beans>

控制台输出:

Exception in thread "main" org.springframework.beans.factory.BeanIsAbstractException: Error creating bean with name 'address': Bean definition is abstract
at org.springframework.beans.factory.support.AbstractBeanFactory.checkMergedBeanDefinition(AbstractBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:285)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at com.itdoc.spring.extendsinfo.Main.main(Main.java:16)

原因:address 成为了模板 bean , 不可以实例化。

 <?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 id="address" p:city="DaLian" p:street="ShaHeKou"/> <bean id="address1" class="com.itdoc.spring.extendsinfo.Address" p:street="GanJingZi" parent="address"/> </beans>
 package com.itdoc.spring.extendsinfo;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:55
*/
public class Main { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("beans_extends.xml");
Address address = (Address) app.getBean("address1");
System.out.println(address); }
}

控制台输出:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'address' defined in class path resource [beans_extends.xml]: Instantiation of bean failed; nested exception is java.lang.IllegalStateException: No bean class specified on bean definition
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'address' defined in class path resource [beans_extends.xml]: Instantiation of bean failed; nested exception is java.lang.IllegalStateException: No bean class specified on bean definition
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.itdoc.spring.extendsinfo.Main.main(Main.java:15)
Caused by: java.lang.IllegalStateException: No bean class specified on bean definition
at org.springframework.beans.factory.support.AbstractBeanDefinition.getBeanClass(AbstractBeanDefinition.java:372)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:66)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
... 13 more

原因:父 bean 中的 class 属性忽略 , 该 bean 必须是 abstract="true" 的。

Bean 依赖:

  • Spring 允许用户通过 depends-on 属性设定 bean 前置依赖的 bean , 前置依赖的 bean 会在本 bean 实例化前创建好。
  • 如果前置依赖于多个 bean , 则可以通过逗号或空格的方式配置 bean 的名称。
 <?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 id="person" class="com.itdoc.spring.extendsinfo.Person" p:name="华崽儿" p:car-ref="car" p:address-ref="address"/>
<bean id="address" class="com.itdoc.spring.extendsinfo.Address" p:city="DaLian" p:street="ShaHeKou"/>
<bean id="car" class="com.itdoc.spring.beans.Car" p:brand="8手奥拓" p:price="3000" p:maxSpeed="120"/> </beans>
 package com.itdoc.spring.extendsinfo;

 import com.itdoc.spring.beans.Car;

 /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:47
*/
public class Person { private String name; private Address address; private Car car; 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;
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
} public Person() {
System.out.println("I am Person Constructor...");
} @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", address=" + address +
", car=" + car +
'}';
}
}
 package com.itdoc.spring.extendsinfo;

 /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:48
*/
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;
} public Address() {
System.out.println("I am Address Constructor...");
} @Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}
}
 package com.itdoc.spring.beans;

 /**
* 集合中的对象
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-02-28 19:56
*/
public class Car { private String brand; private double price; private int maxSpeed; public String getBrand() {
return brand;
} public void setBrand(String brand) {
this.brand = brand;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
} public int getMaxSpeed() {
return maxSpeed;
} public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
} public Car() {
System.out.println("I am Car Constructor...");
} @Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
", maxSpeed=" + maxSpeed +
'}';
}
}
 package com.itdoc.spring.extendsinfo;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* http://www.cnblogs.com/goodcheap
*
* @author: Wáng Chéng Dá
* @create: 2017-03-01 20:55
*/
public class Main { public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("beans_extends.xml");
Person person = (Person) app.getBean("person");
System.out.println(person); }
}

控制台输出:

I am Person Constructor...
I am Address Constructor...
I am Car Constructor...
Person{name='华崽儿', address=Address{city='DaLian', street='ShaHeKou'}, car=Car{brand='8手奥拓', price=3000.0, maxSpeed=120}}

 <?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 id="person" class="com.itdoc.spring.extendsinfo.Person" p:name="华崽儿" p:car-ref="car" p:address-ref="address" depends-on="car, address"/> <bean id="address" class="com.itdoc.spring.extendsinfo.Address" p:city="DaLian" p:street="ShaHeKou"/> <bean id="car" class="com.itdoc.spring.beans.Car" p:brand="8手奥拓" p:price="3000" p:maxSpeed="120"/> </beans>

控制台输出:

I am Car Constructor...
I am Address Constructor...
I am Person Constructor...
Person{name='华崽儿', address=Address{city='DaLian', street='ShaHeKou'}, car=Car{brand='8手奥拓', price=3000.0, maxSpeed=120}}

根据控制台输出我们不难看出 bean 的初始化顺序发生了改变 , 前置依赖的 bean 会在本 bean 实例化前创建好。

Spring学习--Bean 之间的关系的更多相关文章

  1. [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  2. Spring 学习笔记(五)—— Bean之间的关系、作用域、自动装配

    继承 Spring提供了配置信息的继承机制,可以通过为<bean>元素指定parent值重用已有的<bean>元素的配置信息. <?xml version="1 ...

  3. Spring Bean之间的关系

    bean之间的关系:继承和依赖继承bean的配置 Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父bean的bean称为子bean 子bean从父bean中继承配置,包括 ...

  4. Spring(九):Spring配置Bean(二)自动装配的模式、Bean之间的关系

    XML配置里的Bean自动装配 Spring IOC容器可以自动装配Bean,需要做的仅仅是在<bean>的autowire属性里指定自动装配的模式,模式包含:byType,byName, ...

  5. 峰Spring4学习(5)bean之间的关系和bean的作用范围

    一.bean之间的关系: 1)继承: People.java实体类: package com.cy.entity; public class People { private int id; priv ...

  6. 3.spring:自动装配/Bean之间的关系/作用域/外部文件/spel/

    1.自动装配/手动装配 xml配置文件里的bean自动装配 Spring IOC 容器里可以自动的装配Bean,需要做的仅仅是在<bean>的autowire属性里面指定自动装配模式 -& ...

  7. Spring初学之bean之间的关系和bean的作用域

    一.bean之间的关系 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="h ...

  8. Spring - 配置Bean - 自动装配 关系 作用域 引用外部属性文件

    1 Autowire自动装配1.1 使用:只需在<bean>中使用autowire元素<bean id="student" class="com.kej ...

  9. Spring_自动装配 & bean之间的关系 & bean的作用域

    1.自动装配 beans-autowire.xml <?xml version="1.0" encoding="UTF-8"?> <beans ...

随机推荐

  1. HBase Scan,Get用法

    Scan,get用法 1. get help帮助信息 从下列get用法信息可以看出 get 后面可以跟table表名,rowkey,以及column,value.但是如果想通过get直接获取一个表中的 ...

  2. 11 TCP实现QQ聊天

    1.客户端参考代码 #coding=utf-8 from socket import * # 创建socket tcpClientSocket = socket(AF_INET, SOCK_STREA ...

  3. 2016.01.04接触spring一年开始读spring源码

    http://www.cnblogs.com/xing901022/p/4178963.html#_label0 遇到第一个问题The processing instruction target ma ...

  4. python基础——重访类型分类

    python基础--重访类型分类 对象根据分类来共享操作:例如,字符串.列表和元组都共享诸如合并.长度和索引等序列操作. 只有可变对象(列表.字典和集合)可以原处修改:我们不能原处修改数字,字符串.元 ...

  5. Java并发基础--Thread类

    一.Thread类的构成 Thread类实现Runnable接口.部分源码如下: 二.Thread类常用方法 1.currentThread()方法 currentThread()方法可以返回代码段正 ...

  6. 分享 go语言爬虫---开源项目Pholcus

    写在开头的话:记录一下最近学习Pholcus(https://github.com/henrylee2cn/pholcus)的过程,首先去学习的go基本语法,在没接触的时候发现很多不理解的地方,但是当 ...

  7. 图的同构 (Graph Isomorphism)

    整理摘自:https://www.jianshu.com/p/c33b5d1b4cd9 同构是在数学对象之间定义的一类映射,它能揭示出在这些对象的属性或者操作之间存在的关系.若这两个数学结构之间存在同 ...

  8. Leetcode 678.有效的括号字符串

    有效的括号字符串 给定一个只包含三种字符的字符串:( ,) 和 *,写一个函数来检验这个字符串是否为有效字符串.有效字符串具有如下规则: 任何左括号 ( 必须有相应的右括号 ). 任何右括号 ) 必须 ...

  9. HTML如何给table添加滚动条

    HTML如何给table添加滚动条 要给table添加滚动条其实很简单,主要是给table放到一个div里去,然后再设置div显示滚动条即可.示例代码如下所示: <!--div比table大小要 ...

  10. 完整Android开发基础入门博客专栏

    博客地址:http://www.runoob.com/w3cnote/android-tutorial-contents.html