Spring 笔记2---Bean的定义及范围

本文深入探讨了Spring框架中Bean的依赖注入机制,包括如何使用depends-on属性解决特定Bean实例化的顺序问题,抽象及子Bean定义的概念,以及如何利用alias别名降低应用与受管Bean之间的耦合性。此外,文章还详细介绍了如何从配置properties文件中读取属性,并在Spring环境中管理Bean的作用范围,包括singleton、prototype、request、session和globalSession等不同作用域。

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的实例化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值