Spring研究 (4) Bean的配置

博客介绍了Spring中Bean的配置和初始化方法。Spring逻辑层采用Java Bean,正确配置很重要。配置方式有通过Bean的Constructor创建和通过Factory创建,创建的Bean分Singleton和non - singleton。初始化方式有setProperty和指定构造或工厂方法参数,推荐用setProperty。

Spring的逻辑层不是EJB等重量级组件,而是Java Bean,因此正确配置Bean在Spring中就很重要。Spring中Bean的配置一共有以下方式:

第一类:通过Bean的Constructor创建Bean:

创建一个名为exampleBean,类型为examples.ExampleBean的Bean:

<bean id="exampleBean" class="examples.ExampleBean" />

相当于:

exampleBean = new examples.ExampleBean();

缺省的,创建的Bean都是Singleton,如果要每次创建新的Bean,设置:

<bean id="..." class="..." singleton="false" />

对于Singleton的Bean,Spring会跟踪它,下次请求这个Bean时会直接返回Singleton实例。对于non-singleton的Bean,Spring不会跟踪它,每次请求都会创建新的实例。

第二类:通过Factory创建Bean:

如果要通过static factory创建Bean,指定Factory Class和static factory method即可:

<bean id="exampleBean"
class="examples.ExampleBean2"
factory-method="create" />

相当于:

exampleBean = examples.ExampleBean2.create();

如果不是通过static factory而是工厂实例来创建,指定工厂实例和factory method即可,其中引用的factory-bean应该用<bean id="myFactoryBean" ... />配置好了:

<bean id="exampleBean"
factory-bean="myFactoryBean"
factory-method="create" />

相当于:

myFactoryBean = ...
exampleBean = myFactoryBean.create();

初始化Bean

当创建了一个Bean后,立即可以初始化Bean,有两种方式:通过一系列的setProperty(value)和指定Constructor或工厂方法的参数。Spring同时支持这两种方式,但是设计者建议,除非是历史遗留的Bean,推荐使用setProerty的方式初始化Bean。

假定Bean有一个setAge(int age)方法,可以这样初始化Bean:

<bean id="exampleBean" ...>
<property name="age"><value>20</value></property>
</bean>

这是int,float等基本类型和String,Date的初始化方式,如果是一个对象引用,比如setStudent(Student std):

<bean id="exampleBean" ...>
<property name="student"><ref bean="studentBeanId" /></property>
</bean>

特别注意null引用不能用<value></value>,这会被识别为空字符串"",应该用<null/>:

<bean id="exampleBean" ...>
<property name="student"><null/></property>
</bean>

:我也是看Spring的官方文档边看边写出来的,如有错误,还请大家指正!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值