2種方式
-BeanFactory
XMLBeanFactory(newFileSystemResource..)
-ApplicationContext
ClassPathXmlApplicatioContext("foo.xml");
FileSystemXmlApplicationContext("c:/foo.xml");
注入屬性
通過構造函數
-<constructor-arg value="15">
-<constructor-arg ref="xxx">
set注入
-<property name="song" value="15">
-<property name="song" ref="xxx">
spring 裝配支持的集合類型
- <list>
- <set>
- <map>
- <props> 鍵值對,不過都是string類型
對應於配置文件中,以instruments爲例
<property name="instruments">
<list>
<ref bean="guitar"/>
<ref bean="cymbal"/>
<ref bean="harmonica"/>
</list>
</property>
set類似
<map>
<entry key="GUITAR" value-ref="guitar"/>
<entry....>
</map>
entry: key key-ref, value value-ref.
<prop key="GUITAR">STRUM STRUM STRUM</prop>
設置屬性值爲空:
<property name="someNonNullProperty"><null/></property>
自動裝配
byName
<bean id="kenny" class="xxx">
<property name="instrument" ref="saxophone"/>
</bean>
<ben id="instrument" class="xxx">
則上面可變爲:
<bean id="kenny" class="xxx" autoware="byName">
byType
constructor
autodetect
默認自動裝配
<beans default-autowire="byName">
...
控制Bean創建
每次都創建一個新的bean
<bean id=".." calss="..."
scope="prototype"/>
scope
singleton :一個實例
prototype :多個實例
request :http請求
session :http會話
global-session :全局http會話
單例類
factory-method="getInstance" />
初始化和銷燬
<bean id="xxx" class="xxx"
init-method="init"
destroy-method="clean">
高級Bean裝配
abstract="true" 爲抽象類
<bean id="xxx" parent="xxx.class"> 聲明該bean的父類是什麼
可以覆蓋相應屬性值。