spring in action第三版读书笔记
spring会调用默认的构造函数来实例化bean,如果需要使用指定的构造函数可以使用<constructor-arg value=""/>或者<constructor-arg ref="">来进行构造函数的参数指定,前者直接指定某个值,后者指定某个bean作为参数
我们也可以指定其他的函数来实例化bean
<bean id="state" class="com.springinaction.State" factory-method="getInstance"/>
bean的范围;
singleton:每个spring容器中,bean只实例化一次,该方式为默认方式
prototype:每次请求都会实例化bean一次
request:实例存在于request范围内
session:实例存在于session范围内
global-session:在portlet上下文类有效,Portlet规范定义了全局Session的概念,它被所有构成某个portlet web应用的各种不同的portlet所共享。在global session作用域中定义的bean被限定于全局portlet Session的生命周期范围内。如果你在web中使用global session作用域来标识bean,那么web会自动当成session类型来使用
bean的初始化以及销毁:
init-method以及destory-method可以用来指定初始化以及销毁bean的方法
<bean id="auditorium" class="com.springinaction.Auditorium" init-method="initMethodName" destory-method="destoryMethodName"/>
init-method会在bean实例化后最先执行,destory-method会在bean从context中移除之前执行
指定bean的初始化和销毁方法还可以通过集成InitializingBean接口和DisposableBean接口,并实现方法afterPropertiesSet()和destory()
通过元素<beans>的default-init-method和default-destory-method属性我们可以指定全局的初始化方法和销毁方法
通过spring的p namespace来绑定bean的属性,跟用<property>差不多
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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 id="kenny" class="com.springinaction.springidol.Instrumentalist"
p:song = "Jingle Bells"
p:instrument-ref = "saxophone" />
</beans>
绑定集合:
spring中集合的标签:
<list>
<set>
<map>
<props>
<list>和<set>标签可以绑定任何继承Collection的集合,甚至可以绑定到数组,不同的是<list>标签内可以有相同的元素,<set>标签内不能有相同的元素
<bean id="hank" class="com.springinaction.Hank">
<property name="instruments">
<list>
<ref bean="guitar"/>
<ref bean="cymbal"/>
<ref bean="harmoinica"/>
</list>
</property>
</bean>
<bean id="hank" class="com.springinaction.Hank">
<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>
key使用字符串作为key值
key-ref引用一个bean作为key的值
value使用字串作为value的值
value-ref引用一个bean作为value的值
使用props绑定Properties类型
private Properties instruments;
public void setInstruments(Properties instruments) {
this.instruments = instruments;
}
<bean id="hank" class="com.springinaction.springidol.OneManBand">
<property name="instruments">
<props>
<prop key="GUITAR">STRUM STRUM STRUM</prop>
<prop key="CYMBAL">CRASH CRASH CRASH</prop>
</props>
</property>
</bean>