装配bean

spring是一个基于容器的框架,从spring 3.0开始,spring容器提供了两种装配bean的方式,即XML作为配置文件和基于Java注解的配置方式。

1.声明bean

在XML文件中声明bean时,spring配置文件的根元素是来源于spring beans命名空间所定义的<beans>元素,以下是一个例子:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!--bean declarations go here-->
<bean id="duke" class="com.springinaction.springidol.Juggler"/>
</beans>

 2.注入bean

通过<constructor-arg>元素来注入对象的参数。例如:

<bean id="duke" class="com.springinaction.springidol.Juggler"
<constructor-arg value="15">
/bean>
还可以用ref引用另外一个对象。
<constructor-arg ref="beanid">
3.初始化和销毁bean
为bean定义初始化和销毁操作,只需要使用init-method和destroy-method参数来配置<bean>元素。例如:
<bean id="auditorium" 
  class="com.springinaction.springidol.Auditorium"
  init-method="turnOnLigths"/>
4.注入
在spring中可以使用<property>元素配置bean的属性。
<property>在许多方面都与<constructor-arg>类似。spring还可以装配集合,如List,Set,Array。
装配List
<bean id="hank"
    class="com.springinaction.springidol.OneManBand">
    <property name="instruments">
      <list>
          <ref bean="guitar">
          <ref bean="cymbal">
          <ref bean="hardmonica">
      </list>
    </property>
</bean>
 

装配map

<bean id="hank"
    class="com.springinaction.springidol.OneManBand">
    <property name="instruments">
      <map>
          <entry key="GUITAR" value-ref="guitar">
          <entry key="CYMBAL" value-ref="cymbal">
          <entry key="HARDMONICA" value-ref="hardmonica">
      </map>
    </property>
</bean>

 

 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值