autowire自动装配,自动牵线连接。
自动装配的类型:ByType,ByName,constructor(较复杂,暂时跳过)
byName举例:
如果Person中有一个car属性,在xml中定义了一个id为car的bean,则Person中的car属性会被自动装配为定义了的id为car的bean。
byType类似,如果遇到相同类型的bean则自动装配。
注意不管是byName还是byType,当遇到一个以上的可装配数据时,会报异常。
Autowire缺点:
由于自动适配功能只能选byType,byName,constructor中的一种,不可同时使用两种。
且有1个以上可以匹配统一数据时会抛出异常。
一旦为一个bean设置了自动装配,则该bean的所有属性都会进行自动装配,不可以设置部分自动装配。
由于以上缺点,在自己实际写代码时自动装配用的并不多。但是在组合其他框架时会用到。
Bean的继承
bean有一个属性parent,可以从其他的节点继承配置信息,当然继承的前提是继承关系的两个bean的属性必须相同。
abstract是可选的,如果设置为true,则只能作为模板使用,不能被IoC容器实例化。
仅仅作为模板时,class属性可以不需要。
<bean id="car" class="spring2.Car" p:carname="QQ" abstract="true"></bean>
<bean id="subcar" parent="car"/>
depends-on属性
depends-on属性指定的bean,会在当前bean实例化之前被实例化。
bean的作用域
作用于分为:singleton,prototype,request,session,globalSession,applicationIoC容器默认的作用域为singleton,这个同设计模式中的概念不大一样,这里的单例是指一个IoC容器中只有一个实例。
prototype的意思是每当获取Bean的时候,就会深拷贝创建一个实例。
后面几个是web中使用的,application是ServletContext范围,globalSession是Portlet范围的。
<bean id="car" class="spring2.Car" scope="singleton"/>
使用外部属性文件
SpringBean中有时需要混合使用系统部署的配置信息,比如其他框架的properties文件等等。通过PropertyPlaceholderConfigurer的BeanFactory后置处理器,可以将操作系统,或者其他框架的配置信息读取使用。
通过PropertyPlaceholderConfigurer加载属性文件后,可以在Bean配置文件中使用${var}形式的变量,并且可以通过${propName}的形式可以实现相互引用。如下面实例:首先导入context命名空间,然后通过context:property-placeholder 设置事先配置好的config.properties文件。然后就可以通过${carname}的形式来引用在config.properties中定义的数据啦。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:property-placeholder location="classpath:config.properties"/>
<bean id="car" class="spring2.Car" p:carname="${carname}"/>
</beans>
<完>