装配Bean
声明Bean
创建Spring配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://localhost:8080/schema/www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://localhost:8080/schema/www.springframework.org/schema/context/spring-context.xsd">
</beans>
构造器注入
<bean id="pieticDuke" class="com.springinaction.springidol.PoemticJuggler">
<constructor-arg value="15"/>
<contructor-arg ref="sonnet29"/>
</bean>
通过工厂方法创建Bean
当只能通过静态工厂方法来实例化一个对象时,spring支持通过元素的factory-method属性来装配工厂创建的Bean。
Bean的作用域
<bean id="ticket" class="com.springinaciton.springidol.Ticket" scope="prototype"/>
初始化和销毁Bean
<bean id="auditorium" class="com.springinaciton.springidol.Auditorium"
init-method="turnOnLights"
destroy-method="turnOffLights"/>
注入Bean属性
装配list集合
<bean id="hank" class="com.springinaciton.springidol.OneManBand">
<property name="instruments">
<list>
<ref bean="guitar" />
<ref bean="cymbal" />
<ref bean="harmonica" />
</list>
</property>
</bean>
装配map集合
<bean id="hank" class="com.springinaciton.springidol.OneManBand">
<property name="instruments">
<map>
<entry key="GUITAR" value-ref="guitar" />
<entry key="CYMBAL" value-ref="cymbal" />
<entry key="HARMONICA" value-ref="harmonica" />
</map>
</property>
</bean>
装配properties集合
Properties类提供和Map大致相同的功能,但是它限定键和值必须为String类型。
<bean id="hank" class="com.springinaciton.springidol.OneManBand">
<property name="instruments">
<props>
<prop key="GUITAR">STRUM STRUM STRUM</prop>
<prop key="CYMBAL">CYMBAL CYMBAL CYMBAL</prop>
<prop key="HARMONICA">HARMONICA HARMONICA HARMONICA</prop>
</props>
</property>
</bean>
装配空值
<property name="someNonNullProperty"><null/></property>
使用表达式装配
SpEL是一种强大、简洁的装配Bean的方式,它通过运行期执行的表达式将值装配到Bean的属性或构造器参数中。#{}标记会提示Spring这个标记里的内容是SpeEL表达式。
SpEL的基本原理
<property name="message" value="the value is #{5}"/>
在一个SpEL表达式中使用Bean的引用来获取Bean的属性。
<bean id="carl" class="com.springinaciton.springidol.Instrumentalist">
<property name="song" value="#{kenny.song}"/>
</bean>
在SpEL中避免抛出空指针异常的方法是使用null-safe存取器:
`
在SpEL中,使用T()运算符会调用类作用域的方法和常量。