1. depends-on属性
设置依赖关系的bean,如果存在多个依赖对象,用逗号,分号或空格隔开.如
<bean id="testBean1" class=.... depends-on="testBean2,testBean3"/>
可以解决有特殊关系的两个或多个Bean的实例化顺序问题,假如以上代码不加入depends-on属性,就必须要求testBean2,testBean3要在testBean1之前实例化,所以定义必须在testBean1前。
<bean id="testBean2" class.../> <bean id="testBean3" class.../> <bean id="testBean1" class...> <property name="testBean2" ref="testBean2"/> <property name="testBean3" ref="testBean3"/> </bean>
这样会带来代码维护的不方便,所以最好的办法是启用depends-on。
2. 抽象及子Bean定义
Spring允许用显式和隐式方式申明抽象Bean。区别在于显式定义了class属性,而隐式没有。
显式:
<bean id="abstractBean1" class="...." abstract="true"/> <bean id="childBean1" class="...." parent="abstractBean1"/>
隐式:
<bean id="abstractBean1" abstract="true"/> <bean id="childBean1" class="...." parent="abstractBean1"/>
其中parent属性的声明完成了继承关系的映射。
同样的,可以实现“多重”的继承:
<bean id="abstractBean1" class="...." abstract="true"/> <bean id="abstractBean2" class="...." parent="abstractBean1" abstract="true"/> <bean id="childBean3" class="...." parent="abstractBean2"/>
这样childBean3也就同时拥有了Bean1和Bean2的属性。
3. alias别名
能降低应用和受管Bean间的耦合性。
<bean id="testBean" class="....."/> <alias name="testBean" alias="tb"/>
也可以通过别名获得该Bean
ITestBean tb = (ITestBean)factory.getBean("tb");
4.读取配置properties文件属性
例如userinfo.properties内容如下
db.username=scott db.password=tiger
那么可以通过Spring的PropertyPlaceholderConfigurer实现BeanFactoryPostProcessor接口来对文件进行管理
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>userinfo.properties</value> </list> </property> </bean>
配置好后,就可以通过声明以下Bean来获取userinfo信息
<bean name="userinfo" class....> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean
*Spring已经提供了<context:property-placeholder/>元素来代替配置PropertyPlaceholderConfigurer对象了
<context:property-placeholder location="userinfo.properties"/>
*<context:property-override/>元素是检查properties中是否存在需要覆盖的属性致,有则替换覆盖,没有则保留受管Bean中的对应属性。
<context:property-override location="ui.properties"/> <bean name="userInfo" class...> <property name="username" value="un"/> <property name="password" value="pw"/> </bean>
5. 受管Bean的作用范围
singleton 默认的 <bean/>定义
prototype DI容器不会主动实例化prototype受管Bean
request
session
globalSession
*lazy-init="true" 并不意味着构造IOC容器时这一个<bean/>不会被实例化,因为如果BeanA需要引用BeanB,A未启用延迟加载,而B启用了。当容器在完成A实例化时,容器发现它引用了B,因此容器会马上实例化B.无论B是否设定了延迟加载,只要A需要它,容器就会毫不犹豫的去完成B的实例化。