More Related Content
Similar to Spring 2.0 技術手冊第三章 - IoC 容器
Similar to Spring 2.0 技術手冊第三章 - IoC 容器 (8)
More from Justin Lin (20)
Spring 2.0 技術手冊第三章 - IoC 容器
- 1. 。能功等播傳與理處的件事、析解
息 訊 字 文、得 取 的 源 資 是 像,性 特 的 架 框 式 程 用 應 多 更 援 支 並,外 之
能功理管器容的本基 如備具了除
BeanFactory ApplicationContext
,) (架框式程用應個一為作,面方一另在
A pplication framework
。理管與態組的 種各行進器容
Bean Spring
用使何如到解了以可將,中節章個一這在,在所點重的 解 Spring
了是用運的 與
ApplicationContext 悉熟,上用使的器
BeanFactory
容 心 核 在。係 關 賴 依 的 間 之 件 物 及 以,期 週 命 生 的 件 物 個 各 理 管 助 協
以可,念概的 了作實,)IoC (器容個一是心核的
C ontainer Spring
IoC 容器
3
- 2. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
3.1 Bean 基本管理
賴依「謂何解了致大並,式程
2 個一第成完際實經已中章 第在 Spring
, 理管來能功器容的 )
用使何如、 ( 入注
」
D ependency Injection Spring Bean
,式方定設的中 在 於關有多更到習學會將,中當節小個一這在 Bean Spring
。期週命生及以
3.1.1 BeanFactory、ApplicationContext
護維,成生、入載的件物理管,檔義定 取讀責負
BeanFactory Bean Bean
應 的 單 簡 於 對, 期 週 命 生 的 責 負, 係 關 賴 依 的 間 之 件 物 與 件 物
Bean Bean
上 理 管 的 件 物 在, 理 管 來 夠 足 經 已 就
BeanFactory 用 使,說 來 式 程 用 Bean
:叫呼 以 可 法 方 個 六 了 括 包 面 介 , 性便方 的 多 許 得 獲 以 可 就
B eanFactory
boolean containsBean(String)
試測 BeanFactory 的稱名定指所括包否是中 Bean 。
Object getBean(String)
定指 Bean 的應對相得取可即,稱名的定設中檔義定 Bean 。例實
Object getBean(String, Class)
的 應 對 相 得 取,稱 名 的 定 設 中 檔 義 定 定 指
Bean Bean (換 轉 並,例實 C ast )
。別類的定指至
Class getType(String name)
定指 Bean 的應對相得取,稱名的定設中檔義定 Bean 之 Class 。例實
boolean isSingleton(String)
定指 Bean 的定指試測,稱名的定設中檔義定 Bean 之 scope 為否是
Singleton 。)明說會中 的 在後之(
Bean scope
String[] getAliases(String)
3 2
- 3. Chapter 3 IoC 器容
該得取,稱名的定設中檔義定
Bean 定指 Bean 在後之(名別的有所 Bean
。)明說會中名別與稱名別識的
,的夠不是能功的理管器容 供提只,架框式程用應個一為作過不 Bean
用使以可則,能功器容的階進及以色特些一的供提所
Spring 用利要若
。
org.springframework.context.ApplicationContext ApplicationContext
間之 護 維 , 檔 義 定 取讀 責 負 有 具 也 , 立 建 而
BeanFactory 於基 Bean Bean
的 需所式 程 用 應 個 一 供 提 還 此除, 能 功 等 係 關 賴 依 的
ApplicationContext
: 如例, 能 功 架 框 的 整 完 更
(案檔源資得取供提
R esource file 。法方的便方更)
。法方的析解息訊字文供提
。息訊) (化際國援支
I nternationalization, I18N
的 趣 興 感 件 事 對,件 事 佈 發 以 可
ApplicationContext Bean 些這到收接以可
。件事
Spring 者始創的 Rod Johnson 代取來 ApplicationContext
用使議建
BeanFactory 作實在, 是 概大的 用 使 常 最 , 中 別 類 的
ApplicationContext
:個三下以
org.springframework.context.support.FileSystemXmlApplicationContext
定指可 XML 。檔義定取讀來徑路對絕或徑路對相的檔義定
org.springframework.context.support.ClassPathXmlApplicationContext
從 Classpath 取讀來中徑路定設 XML 。檔義定
org.springframework.web.context.support.XmlWebApplicationContext
在 Web 。檔義定取讀來置位對相定指,中構架案檔的中式程用應
個一第的成完所中章 第將以可,說來子例的單簡個舉 2 Spring 中式程
:容內的下以為改修別類
SpringDemo 的
3 3
- 4. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(
"beans-config.xml");
HelloBean hello =
(HelloBean) context.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
ApplicationContext 化例實在以可,檔義定 個多取讀以可 Bean
ApplicationContext :如例,置位的檔義定 定指列陣以,時別類作實的 Bean
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"beans-config.xml", "beans-config2.xml"});
、 用使以可您 file:/ classpath: 等 至甚
http:// URL 至甚,置前
的有所示表,
classpath*: Classpath :配匹都徑路置前
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath*:beans-config.xml");
有所下 *取讀可子例的下以如例,元字 定指以可也 Classpath " beans"
果 如,用 有 中 統 系 案 檔 的 際實在 只 是 的 意 注 要 但 , 案 檔 定 設
XML 的頭開
. jar :效無就定指的下以則,話的中案檔 在是
ApplicationContext context =
new ClassPathXmlApplicationContext("beans*.xml");
3 4
- 5. Chapter 3 IoC 器容
與 將只 前 先 您 果 如
spring-beans.jar spring-core.jar 至入加 Classpath
將須必 還 , 式 程 的 上 以 行執與 譯 編 能 了 為 則 , 中 spring-context.jar 入加
Classpath 。中定設的 至
用使上以議建隊團發開 Bean,時檔義定 個多要需當
Spring
不, 立 獨 自 各 間 之 檔 義 定 是 處 好 , 取 讀 來 式 方 的
ApplicationContext Bean
:如例,籤標 用使是 式 方 的 代 替 個 一 另。在 存 的 此 彼 到 識 意 用 < import>
<beans ...>
<import resource="dao-config.xml"/>
<import resource="resources/messageSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
個 一 同 在 置 放 須 必 檔 義 定, 前 之 籤 標
<import> 在置放須必籤標
< bean>
義 定 個 每 而 ,置 位 檔 義 定 定 指 徑 路 對 相 以 ,中 之
Classpath 是或錄目
Bean
。籤標根
< beans> 括包須必都容內的檔
換替 用使何如,時式程寫撰在紹介先邊這在 ApplicationContext
等 佈 發 的 件 事、 理 管 的 息 訊 字 文 於
BeanFactory ApplicationContext 於 關,
。 紹 介 一 一 中 題 主 的關相 後 往 在 將 也 , 能 功
3.1.2 Bean 的識別名稱與別名
當,稱名別識的 定指 用使以可時籤標 用使中檔義定在
< bean> " id" Bean
的上稱名免以,式方名命的稱名 範規好最,時檔義定 個多要需您
Bean " id"
定 在慮考如例,名別定設 為以可還您,後之性屬 定設在。突衝
" id" Bean A
參要中檔義定 在而,例實 的 個一考參要中檔義
" device:dataSource" Bean B
應在例實的 上際實但,例實 的
" user:dataSource" 個一考
Bean DataSource
3
- 6. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
定指例實該為式方的名別用使以可就則,個一在存只中式程用
:如例,稱名的
"device:dataSource"與 " user:dataSource"
<beans ...>
<bean id="app:dataSource" class="..."/>
<alias name="app:dataSource" alias="device:dataSource"/>
<alias name="app:dataSource" alias="user:dataSource"/>
...
</beans>
:如例 , 名 別 至 考 參 接 直 以 可 , 中 檔 義 定 在 則
A
<beans ...>
<bean id="device:someBean" class="...">
<property>
<ref bean="device:dataSource">
</property>
</bean>
...
</beans>
: 如例, 名 別 個 一 另 至 考 參以 可 也 , 中 檔 義 定 在
B
<beans ...>
<bean id="user:otherBean" class="...">
<property>
<ref bean="user:dataSource">
</property>
</bean>
...
</beans>
個一同是的考參上際實而,範規定設稱名的己自有擁以可檔義定個兩
用使接直以可還,外之名別定設籤標
Bean < alias> 用使了除,例實 < bean>
:如 例 , 隔 區 號 逗 以 間之名 別 個 多 而 , 名 別 定 設 來 性 屬
" name" 的籤標
<beans ...>
<bean id="app:dataSource"
name="device:dataSource,user:dataSoource" class="..."/>
...
</beans>
3 6
- 7. Chapter 3 IoC 器容
3.1.3 Bean 的實例化
個一化例實要中 在
Spring Bean 到看 所 止 為 前 目 到 , 式 方 種 幾 有 以 可
:式方的本基最是的
<bean id="writer" class="onlyfun.caterpillar.FloppyWriter"/>
的數參有沒是就也,式構建設預用使會將 ,式方定設的樣這依
S pring
。 明說會將節一下,定設的式構建的數參有於關(例實 立建來式構建
) Bean
來) ( 法 方 廠 工 態 靜 過 透是式 方 種 一 的 上 計 設 在s tatic factory method
細的立建件物解了用不件物的法方廠工態靜叫呼是處好,件物個某得取
:面介 IMusicBox個一 計 設 以 可 如 例 , 節
StaticFactoryMethodDemo IMusicBox.java
package onlyfun.caterpillar;
public interface IMusicBox {
public void play();
}
個一了計設您設假 MusicBoxFactory 得取, IBox 的它由節細的例實
:責負法方態靜
createMusicBox()
StaticFactoryMethodDemo MusicBoxFactory.java
package onlyfun.caterpillar;
public class MusicBoxFactory {
public static IMusicBox createMusicBox() {
return new IMusicBox() {
public void play() {
System.out.println(" …樂音琴鋼放撥 ");
}
};
}
}
3 7
- 8. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
若 如 例 , 例 實 得取來 法 方 廠 工 態 靜 用 使 定 設 以 可 也 中
Spring 在 Bean
實的 得取來法方
MusicBoxFactory 的
createMusicBox() 過透要 IMusicBox
:如例,性屬< bean> 的 定設以可則,例
" factory-method"
StaticFactoryMethodDemo beans-config.xml
<?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-2.0.xsd">
<bean id="musicBox"
class="onlyfun.caterpillar.MusicBoxFactory"
factory-method="createMusicBox"/>
</beans>
取確正可否是定設的上以看看,式程試測的單簡個一寫撰以可來下接
IMusicBox :例實的 得
StaticFactoryMethodDemo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans-config.xml");
IMusicBox musicBox = (IMusicBox) context.getBean("musicBox");
musicBox.play();
}
}
3 8
- 9. Chapter 3 IoC 器容
:示所 圖 下 如 果 結 的 行 執
圖 3.1 StaticFactoryMethodDemo 果結行執案專
法方廠工的例實 廠 工 個 某 用 使 要 想 您 果如 , 的 似 類 例 範 個 這 與 Bean
的 用使以可則,例實 得取來)
f actory method Bean ( < bean> " factory-bean"
得取來法方廠工定指性屬 Bean 用使並, 廠工定指性屬
" factory-metod"
Bean :下如段片例範的定設個一如例,例實
<!— 廠工 Bean 有上其, createInstance() --> 法方
<bean id="factoryBean" class="onlyfun.caterpillar.SomeFactory">
...
</bean>
<bean id="some"
factory-bean="factoryBean"
factory-method="createInstance"/>
,中 定 設 的 上 以 在 S pring 化例實會將 " factoryBean" 得取要而, " some"
用使會將,時例實的 " factoryBean"的 createInstance() 。得取來法方
3.1.4 Bean 的 scope
設預例實的得取 Spring 或 從,中 在
BeanFactory ApplicationContext
第在如例,例 實 個一 持 維只 稱名
Singleton 個一 每 為設預是就也, 為 Bean
得取
2 SpringDemo 過透次一每,中案專 章 factory.getBean ("helloBean")
。件物的新個一生產都次一每是不而,件物個一同是都上際實,件物的
什有會不並說來式程的緒行執單對,例實一單生產式模
Singleton 用使
) (全安緒行執到意注須必您,式程的緒行執多於對但,題問麼 T hread-safe
3
- 10. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
通,題問步同不料資的發引所源資用共取存時同緒行執個多止防,題議的
。)
Singleton (的態狀無是都 的
Bean 常
S tateless
或 從次每,定設以可中
Spring 在而然 BeanFactory ApplicationContext
: 如 例,例 實 的 新 個 一 生 產 都 時 得 取 並 名 別 定 指
Bean
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
scope="prototype">
...
為定設其將由藉, Spring 是設預性屬
" scope" ,中 在 "singleton"
。 例實的 新 個 一 生 產 會 都 , 時
"prototype" 得取來稱名定指次每則, Bean
生產定設來, 或 為性屬 < bean> 的 定設由藉以可也您
" singleton" " true" " false"
相了為是要主,式方的性屬 Singleton 定設,式方的 為否是例實
" singleton"
。留保而式方定設
Spring 的本版前先於容
個一持維器容 個一「對針是要主 S pring 的
Singleton ,到意注要 IoC
不
Bean 的到談常上) (式模計設跟,言而」例實
D esign Pattern Singleton
的入 載 所 個每對是的說所, Singleton 的到談上式模計設,同 ClassLoader
。例實個一生產別類
與Spring 2.0 定設以可了除性屬 " scope" ,中 在 " singleton" " prototype"
與 、 定設以可還,境環式程用應
Web 對針,外之 " request" " session"
應 的 於 基 與 段階話 會 、 段 階 求 請 示 表 別 分 ,
"globalSession" Portlet Web
。段階話會式程用
3 1
- 11. Chapter 3 IoC 器容
3.1.5 Bean 的生命周期
用使是果如,段階行執個幾經歷會,毀銷到立建從
Bean 個一
:期週命生的下以援支量儘會,話的 理管、成生來
BeanFactory Bean
Bean 立建的
由
BeanFactory 取讀 Bean 個各成生並,檔義定 Bean 。例實
入注性屬
的關相行執 Bean 。入注賴依性屬
BeanNameAware 的
setBeanName()
Bean 作實 有別類 果如
org.springframework.beans.factory.BeanNameAware
。法方 的它行執則,面介
setBeanName()
BeanFactoryAware 的
setBeanFactory()
Bean 作 實 有 別 類 果 如 org.springframework.beans.factory.
。法方
BeanFactoryAware 的它行執則,面介 setBeanFactory()
BeanPostProcessors 的processBeforeInitialization()
的何任有果如
org.springframework.beans.factory.config.BeanPost-
的例實
Processors 行執則,聯關例實
Bean 與例實 BeanPostProcessors
。法方
processBeforeInitialization()
InitializingBean 的
afterPropertiesSet()
, Bean 作 實 有別類 果如
org.springframework.beans.factory.InitializingBean
。法方 的它行執則
afterPropertiesSet()
Bean 義定中檔義定
init-method
:如例,稱名法方定設性屬
Bean "init-method"
用使檔義定 在以可
...
<bean id="helloBean"
3 11
- 12. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
class="onlyfun.caterpillar.HelloBean"
init-method="initBean">
...
行執會就,時段階個這至行進則,話的定設上以有果如 initBean() 。法方
BeanPostProcessors 的
processaAfterInitialization()
行執則,聯關例實 與例實 的何任有果如
BeanPostProcessors Bean Bean-
。法方
PostProcessors 的例實
processaAfterInitialization()
DisposableBean 的
destroy()
作 實 有 別 類 果 如,時 閉 關 器 容 在
Bean org.springframework.beans.factory.
。法方
DisposableBean 的它行執則,面介 destroy()
Bean 義定中檔義定
destroy-method
法方定設性屬 用 使 檔 義 定 在 以 可,時 閉 關 器 容 在
Bean "destroy-method"
:如例,稱名
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
destroy-method="destroyBean">
...
行執 會就,時段階 個這至行進 則,話的定設 上以有果如 destroyBean() 。法方
的 作 實 與 實 其 , 性 屬 "dohtem-tini" 的 >naeb< 義 定 InitializingBean
,法方始初的 義定以可,者前用採,的同相是義意
afterPropertiesSet() Bean
與,性屬 的
Spring 義定。 的
API 至合耦用不又而
< bean> " destroy-method"
可,者 前 用 採 , 同 相 是 也 義 意 法 方
DisposableBean 的面介
destroy() 作實
Bean 。 的
Spring API 至合耦用不 讓以
為名命都如例,稱名毀銷或稱名始初的定固有都 的有所果如
Bean init()
destroy() 與 義定別分上
< bean> 在必不則, 或
" init-method" " destroy-method"
3 12
- 13. Chapter 3 IoC 器容
在以可而,性屬 < beans> 義定上 " default-init-method" 與 " default-destroy-
:如例,性屬
method"
<beans default-init-method="init"
default-destroy-method="destroy">
....
</beans>
個每行執動自會 ,後之定設的上以如
S pring Bean 的義定所上 init() 與
destroy() 。 夫功的 檔 定 設 寫 撰 少 不 去 省 以 可 , 法 方
,同不有稍則話的 理管並成生來 ApplicationContext 用使是果如 Bean
行執在,話的例實 理管及成生來
ApplicationContext 用使 Bean
作實有上別類 若,後之段階
BeanFactoryAware 的
setBeanFactory() Bean
其行執則,面介
org.springframework.context.ApplicationContextAware
的 行進續繼才著接,法方
setApplicationContext() BeanPostProcessors
。程流的後之及
processBeforeInitialization()
, 中 檔 義 定 叫 呼並前 之 器 容 閉 關 在 想 若 , 中 式 程 用 應 非 在
Web Bean
行執以可則,法方
Singleton Bean 的定設所 的 destroy
向,法方
AbstractApplicationContext 的 registerShutdownHook() JVM
:如 例 , 法 方 關 相 冊 註
AbstractApplicationContext context
= new ClassPathXmlApplicationContext("beans-config.xml");
...
context.registerShutdownHook();
// …式程用應行執
,前之 束 結 式 程 用 應 在 則
B ean 的定設所上檔義定 destroy 被會將法方
。行執叫呼
,時 得 取 正 真 法 方 用使在有只,
BeanFactory 用使果如
getBean() Bean
對針先預會則, 用 使 果 如。作 動 的 化 例 實 作 會 才
ApplicationContext Bean
以 可則, 的 要 想 所 您 是 不 這 果 如 , 化 例 實
Bean 的有所 將 , 容 內 的 檔 義 定
3 13
- 14. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
定設上 在
< bean> 則, 為性屬
" lazy-init" " true" ApplicationContext 在會不就
該對針,時動啟 Bean :如 例 , 作 動 的 化 例 實 作
<bean id="some" class="onlyfun.caterpillar.Some" lazy-init="true">
...
</bean>
3.1.6 Bean 定義的繼承
義 定 的 些 有 ,到 現 發 您 而,長 增 的 斷 不 容 內 的 檔 義 定 果 如
Bean Bean
且,性屬等 與 有 都 義 定 個 幾 好 許也如 例 , 複 重 所 有 實 其
Bean " name" " age"
慮 考以可 則 , 定 設 的 同 不 有 會 個 幾 有 只 , 值的同 相 定 設 是 都 份 部 大
Bean
Bean 。 夫 功的定 設 多 許 去 省 以 可 樣 這 , 義 定 個 某 承 繼
個一了寫撰您設假,承繼的義定 範示來子例的際實個舉
Bean SomeBean
:下如別類
BeanInheritanceDemo SomeBean.java
package onlyfun.caterpillar;
public class SomeBean {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
3 14
- 15. Chapter 3 IoC 器容
}
的份部大中其,例實的 多 許生產 會許也 您
SomeBean SomeBean 其 "name"
: 義定下 如以可 則,同不 個幾有 只 , 與
"age" "guest" 18是都 性 屬 與
BeanInheritanceDemo beans-config.xml
<?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-2.0.xsd">
<bean id="inheritedSomeBean" abstract="true">
<property name="name">
<value>guest</value>
</property>
<property name="age">
<value>18</value>
</property>
</bean>
<bean id="some"
class="onlyfun.caterpillar.SomeBean"
parent="inheritedSomeBean">
<property name="name">
<value>Justin</value>
</property>
</bean>
</beans>
象抽個是這示表, 為性屬 了定 設 中
"inheritedSomeBean" 在 "abstract" "true"
,性屬 了定 設 中
Bean 在而,化例實去試嘗會不 ,義定 的
Spring "some" "parent"
為義定新重性屬 有只,定設的 承繼將它示表
" inheritedSomeBean" " name"
為定設性屬的後最 個這
"Justin" 看看來式程的單簡個寫以可。 " some" Bean
:何
3 1
- 16. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
BeanInheritanceDemo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans-config.xml");
SomeBean some = (SomeBean) context.getBean("some");
System.out.println("name:" + some.getName());
System.out.println("age:" + some.getAge());
}
}
為義定新重被 ,到看中果結行執在以可 " name" " Justin" 而, " age" 繼則
: 是就也, 了承
" inheritedSomeBean" 18
圖 3.2 BeanInheritanceDemo 果結行執案專
的象抽全完個一從了除 Bean 個一從以可也,外之定設關相承繼義定
Bean :如例,承繼來義定之例實
...
<bean id="inheritedSomeBean" class="onlyfun.caterpillar.SomeBean">
<property name="name">
<value>guest</value>
</property>
<property name="age">
<value>18</value>
3 16
- 17. Chapter 3 IoC 器容
</property>
</bean>
<bean id="some"
class="onlyfun.caterpillar.SomeBean"
parent="inheritedSomeBean">
<property name="name">
<value>Justin</value>
</property>
</bean>
,中定設個這在 " inheritedSomeBean" 被以可也 Spring 必有若,化例實
。義定其承繼 它其被以可也,要
Bean
3 17
- 18. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
3.2 Bean 的依賴設定
及 是式方入注賴依的本基種兩中
Spring 在 Setter Injection
了供提還,入注賴依的 非對針外另,
Constructor Injection Singleton
賴依些一及以,入注賴依些這對針將,中節小個這在,
Method Injection
。 明說以 加 式 方 的 定 設 係 關
3.2.1 Type 2 IoC、Type 3 IoC
的 用利,中式程
2 個 一第 的 成 完 所 中 章 第 在
Spring Bean Setter 法方
是就也, 是的勵鼓
S pring ,入注賴依成完
Setter Injection Type 2
的
Dependency Injection用使許允也但, Type 3 Dependency Injection
視是 係 關 賴 依 入 注 來 或
Constructor injection 用使要, Setter Constructor
用使中 在何如看看來先邊這,論討以加再後稍在這,定而求需 Spring
:寫撰何如別類
Constructor injection 看看先首, HelloBean
Type3Demo HelloBean.java
package onlyfun.caterpillar;
public class HelloBean {
private String name;
private String helloWord;
//法方構建數參無有要議建
public HelloBean() {
}
public HelloBean(String name, String helloWord) {
this.name = name;
this.helloWord = helloWord;
}
public void setName(String name) {
this.name = name;
}
3 18
- 19. Chapter 3 IoC 器容
public String getName() {
return name;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
}
法方 構 建 數 參 無 用 使 有 以 可
Bean 讓能要了為,時別類 義定在
Spring
有沒前目使即,法方構建的數參無個一義定以可議建,性彈的件物成生來
。容 內 作 實 的 何 任 寫 撰
的上 法 方 構 建 的 數 參 有個二 第 , 是 的 意 注 要 中 義 定 別 類
HelloBean 在
上定設在,時 B ean 用使中檔義定 ,序順之數參個兩
Constructor Injection
: 示所下 如 , 定 指 來 序 順 的數參 上 法 方 構 建 依 以 可
Type3Demo beans-config.xml
<?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-2.0.xsd">
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg>
<value>Justin</value>
</constructor-arg>
<constructor-arg>
<value>Hello</value>
</constructor-arg>
</bean>
</beans>
3 1
- 20. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
用使將示 表來籤標 用使,中案檔義定在
<constructor-arg> Constructor
有擁時
Injection 如不並 用使於由,
Constructor Injection Setter Injection
方個一另。序順的數參依須必時定指須必以所,稱名的懂易樣這
setXXX()
的中法 方 構 建 至 入 注 將 件 物 定 指 於 用 是 就 性 屬
" index" ,置位引索定指是式
二 第 , 是 值 引 索 的 數 參 個 一 第 , 中 定 指 序 順 的 數參, 數 參 的 置 位 個 一 哪 0
:寫撰麼這以可也中
1 如例,推類此依, 是個
beans-config.xml
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg index="0">
<value>Justin</value>
</constructor-arg>
<constructor-arg index="1">
<value>Hello</value>
</constructor-arg>
</bean>
...
生、 容 內 案 檔 義 定 取 讀 用使, 式 程 主 寫 撰 是 著 接
ApplicationContext
Bean : 示 所 下 如寫撰 的 式 程 , 入 注 係 關 賴 依 成 完 、 例 實 成
Type3Demo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(
"beans-config.xml");
HelloBean hello =
(HelloBean) context.getBean("helloBean");
3 2
- 21. Chapter 3 IoC 器容
System.out.print("Name: ");
System.out.println(hello.getName());
System.out.print("Word: ");
System.out.println(hello.getHelloWord());
}
}
:示所下如果結行執
圖 3.3 Type3Demo 果結行執案專
型數 參 的 上 式 構 建 析 解 動 自 會 , 時 同 相數個 數 參 的 上 式 構 建 當
S pring
: 如 例 , 式 構建個 哪 用 使 要 定 決 以 ,入注 賴 依 的 定 設 所 及 態
...
public class HelloBean {
...
public HelloBean(String name) {
...
}
public HelloBean(Date date) {
...
}
...
}
定指以可時構建在
HelloBean String定指以可也, java.util.Date ,件物
: 定 設麼這 是 中 檔 定 設 在 果 如
3 21
- 22. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
...
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg>
<ref bean="date"/>
</constructor-arg>
</bean>
...
用使並析解動自會 則,件物的態型 入注是中檔定設於由
Date Spring
也 您 , 件 物 的 賴 依 所入注 並 件 物 構 建 來 , 式 構 建 的 數 參 態 型 有
Date Date
: 如 例 , 態型個 哪 用 使 要 定 指 確 明 來 性 屬 用 使 以 可
" type"
...
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg type="java.util.Date">
<ref bean="date"/>
</constructor-arg>
</bean>
...
實其,題問個這入注賴依成完來法方 Constructor 或 Setter用使要於至
或,源資的有所好備準就時立建件物在要:題問的老古個一論討在於等就
。定設行進來法方 用 使再, 後 好 立 建 件 物 在 是
Setter
賴依成完併一時同的件物構建在以可,是一之處好的
Constructor 用使
但,了好備準就也係關賴依的件物它其與它,後立建一件物,立建的係關
留上法方構建在會 用使,多很係關件物的立建要果如
Constructor injection
。擇 選 的 錯 不 個 是 會 法 方 用 使 時 這 , 憶 記 易不且 , 數 參 的 串 長 一 下
Setter
是會件物的入注解瞭以可稱名法方的確明有具法方
S etter ,面方一另
置位數參個某上 setXXX()憶記比會,稱名的樣這 是像,麼什 Constructor
3 22
- 23. Chapter 3 IoC 器容
合 結 當,好 得 來 件 物 個 某 表 代 引 索 的
IDE 程 寫 撰 ,時 用 使 能 功 示 提 法 方 的
。率 效 有 且 便 方 更 會 式
證保能不以所,法方 Setter有供提於由,時法方 用使而然
setXXX()
可員人發開式程為因,定設改更被會不期時行執在源資或員成料資的關相
或 員成料 資 些 一 讓 要 想 果 如以所 , 性 屬 關 相 定 設 來 法 方
Setter 行執接直能
。擇 選 的 單 簡 個 是 會 用 使 ,有私 是 或 讀 唯 為 變 源 資
Constructor injection
3.2.2 依賴的值設定與參考
接直中 或 在以可,時 義定在子例的前之
Bean < property> < constructor>
構建或性屬給) (態型本基或串字個一定指,籤標
< value> 用使 p rimitive
:如例,式
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg>
<value>Justin</value>
</constructor-arg>
<property name="age">
<value>18</value>
</property>
</bean>
...
用使接直以可也您 " value" 比種一是這,值態型本基或串字定指來性屬
: 如例, 式 方 定 設 的 潔 簡 較
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg value="Justin"/>
<property name="age" value="18"/>
</bean>
...
3 23
- 24. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
為性屬 個 某 定 設 要 想 果 如 null 用使以可,值 < null/> :如例,籤標
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<property name="name"><null/></property>
</bean>
...
為定設是不而, 串字空為定設性屬串字將是,式方定設的下以意注 ""
null :
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<property name="name"><value></value></property>
</bean>
...
的義定個一有經已中檔義定 在果如
Bean Bean 某讓接直以可則,例實
: 如 例 ,例實 個 這 至 考 參 性 屬 個
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg>
<ref bean="date"/>
</constructor-arg>
<property name="other">
<ref bean="otherBean"/>
</property>
</bean>
...
用 使 是 ,法寫 的 潔 簡 較 比 個 一 另 " ref" :如例,定指來性屬
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg ref="date"/>
<property name="other" ref="otherBean"/>
</bean>
...
3 24
- 25. Chapter 3 IoC 器容
它其考參 用使望希果如 < ref> Bean 的義定所,時例實 Bean 同在是須必
定 指 以 可則, 中 之 案 檔 定 設 個 一 " local" :如例,性屬
...
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<property name="other">
<ref local="otherBean"/>
</property>
</bean>
...
再 不 中 檔 義 定 在 後 之 ,次 一 考 參 性 屬 個 某 被 只 例 實 的
Bean 個某果如
標 用使時義定性屬在接直以可也麼那,考參所性屬的 它其被
Bean <bean>
:如例,可即性屬
"class" 其定指需僅並,籤
...
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="date">
<bean class="java.util.Date"/>
</property>
</bean>
...
的 Spring IoC 成生動自會器容 Date 過透並,例實 setDate() 將法方 Date
給定設例實 " helloBean"。
個一另於賴依它果如,前之 個某得取在 Bean Bean 去先會就
S pring ,
個 某 果 如。 入 注 賴 依 行 進 並 的 賴 依 被 化 例 實
Bean Bean 求 要, 前 之 成 生 在
定指以可則,化例實先須必 個一另
Bean " depends-on" :如例,定指來性屬
3 2
- 26. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
<bean id="beanOne"
class="onlyfun.caterpillar.BeanOne" depends-on="beanTwo"/>
<bean id="beanTwo" class=onlyfun.caterpillar.BeanTwo" />
設於由但,入注 求要確明有沒並 然雖,中例上在
" beanOne" " beanTwo"
會 ,前之 得取在則,
" depends-on" 為性屬 了定
" beanTwo" " beanOne" S pring
在定設要 的上以個兩有果如,化例實
" beanTwo" 將先 Bean " depends-on"
。隔區號逗以則,中
3.2.3 自動綁定
用使、值態型本基、串字定指
Bean 用使中檔義定 在了除
< value> <ref>
屬 定指並籤標 用使是或,例實 它其至考參定指接直
Bean <bean> "class"
型類過透以可您。定綁動自的式隱援支也 S pring ,件物依相定指來性
應對 它其至定綁例實 個某將,)
b yType b yName (稱 名或) Bean ( Bean
的 定 綁 種 各 範 示,例 為 式 程 的 中 案 專
AutoWireDemo 以 接 直 邊 這,性 屬 的
HelloBean :義定下如別類 設假,式方
AutoWireDemo HelloBean.java
package onlyfun.caterpillar;
import java.util.Date;
public class HelloBean {
private String helloWord;
private Date date;
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
3 26
- 27. Chapter 3 IoC 器容
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
}
中其 HelloBean 的下以在,例實的 個一受接法方
setDate() 的 Date Bean
將, 中 檔 義 定 依作態型依動自
" autowire" 讓, 為定設性屬
" byType" Spring
:定綁賴
AutoWireDemo beans-config.xml
<?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-2.0.xsd">
<bean id="dateBean" class="java.util.Date"/>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean"
autowire="byType">
<property name="helloWord" value="Hello!"/>
</bean>
</beans>
綁動自過透是而,性屬 的 定指有沒並,中檔義定在
" helloBean" Date
的 據根會以所,
"autowire" 了定指上性屬 "byType" 在,定 " helloBean"
的 似類有 義 定 否 是 中 檔 義 定 在 斷 判 來 , 態 型 的 受 接 所 法 方
setDate() Bean
果 如,時 定 綁 動 自 用 使, 的 給 定 設 之 將 並,件 物 態 型
" helloBean" setDate()
"byType" 出丟則,定綁成完法無 org.springrframework.beans.factory.
3 27
- 28. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
UnsatisfiedDependencyExcpetion 程試測的單簡個一寫撰以可。外例
: 成 完否是 係 關 賴 依 看 看 , 式
AutoWireDemo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans-config.xml");
HelloBean hello =
(HelloBean) context.getBean("helloBean");
System.out.print("Word: ");
System.out.println(hello.getHelloWord());
System.out.print("Date: ");
System.out.println(hello.getDate());
}
}
: 示 所下如 面 畫 考 參 果 結 行 執
圖 3.4 AutoWireDemo 果結行執案專
3 28
- 29. Chapter 3 IoC 器容
的時義定 據根會 "byName" 則,定綁來 定指以可也您Spring Bean "id"
來子例個舉,定綁動自行進來致一否是稱名 Setter 與名別的定指上性屬
必 則, 話 的 入 注 賴 依 成 完 來 法 方
"byName" 過透要而 是 果 如,說
setDate()
改修如例,稱名 Bean 為值 的 個一第下一改修須
" id" "date" beans-
config.xml :下如
<?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-2.0.xsd">
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="byName">
<property name="helloWord" value="Hello!"/>
</bean>
</beans>
"byName" 用使果如
的 應對則 , 定 綁 動 自 成 完 法 無 Setter 綁未持維僅
。態狀定
是就 也 , 定 綁 動 自 用 套 時 用使在以可也
Type 3 Dependency Injection
案專 改修若如例,定綁動自行進試嘗以可也上法方構建在 AutoWireDemo
HelloBean :下如別類 的中
package onlyfun.caterpillar;
import java.util.Date;
public class HelloBean {
private String helloWord;
private Date date;
3 2
- 30. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
// 法方構建的數參無個一留保議建
public HelloBean() {
}
public HelloBean(Date date) {
this.date = date;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
}
義定新重後然 beans-config.xml :下如
<?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-2.0.xsd">
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="constructor">
<property name="helloWord" value="Hello!"/>
</bean>
</beans>
3 3
- 31. Chapter 3 IoC 器容
,時係關賴依立建在,
"autowire" 為定設
"constructor" 於由 S pring
型 數參之 上 法 方 構 建 的 關 相 及 , 態 型 例 實
Bean 的中器 容 對 比 圖 試 會 器 容
立建來法方構建該用選則,話的有果如,合符否是上態型在看看,態 Bean
的 個這 與法方構建數參帶的 " helloBean" ,中 子 例 上 以 在 。 例 實
date Bean
注例實 的中檔義定將並,例實構建來法方構建該用選是於,符相態型 date
出丟則,定綁成完法無果如,它給入
org.springframework.beans.factory.
。外例
UnsatisfiedDependencyException
,容內寫撰的檔義定短縮以可,式方的定綁動自些一用運,到看以可
判來 給 交 切 一, 為 定 設 以 可 還,話 的 懶 偷 再 想 還 果 如
"autodetect" Spring
:
beans-config.xml 下一改修如例,斷
<?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-2.0.xsd">
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="autodetect">
<property name="helloWord" value="Hello!"/>
</bean>
</beans>
如用使試嘗會 "autowire" ,時 為定設被
"autodetect" 當S pring
成完有 沒 果 如 , 立 建 的 係 關 賴 依 理 處 來
"autowire" "constructor" 為定設被
來式方的 為定設被 如 用 使 試嘗再 則 , 立 建 係 關 賴 依
"autowire" "byType"
。係關賴依立建
3 31
- 32. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
到看的楚清,中檔義定從法辦沒於由,中定綁動自式隱的紹介上以在
入加以可您,立建實確係關賴依些某定確了為,定設成完都性屬個每否是
四有以可, <bean> 定設時用使籤標 在,查檢依相
"dependency-check"
。 、 、
" simple" 、
" objects":式方查檢依相種
" all" " none"
) (生原是像,係關賴依成完否是性屬的單簡查檢只
"simple" p rimitive
賴依成 完 否 是 性 屬 的 態 型 件 物 查 檢 則 定 設
" objects" ;件 物 串 字 或 態 型 料 資
,值設預是定設 " all" ; 係關賴 依 成 完 否 是 性 屬 的 部 全 查 檢 則 ; 係 關 " none"
。性依相查檢不示表
: 示所下 如 子 例 的 定 設 個 一
<?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-2.0.xsd">
<bean id="date" class="java.util.Date"/>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean"
autowire="autodetect"
dependency-check="all">
<property name="helloWord" value="Hello!"/>
</bean>
</beans>
現發時查檢依相行進果如,定設查檢依相了入加時定綁動自用使旦一
出丟會時式程行執則,係關賴依的成完未有 org.springframework.beans.
。外例
factory.UnsatisfiedDependencyException
,係關賴依的間之件物出看查易容不上檔義定在,定綁動自用使於由
自用使才,時定確未求需或,型原發開速快要需式程用應在有只議建此因
3 32
- 33. Chapter 3 IoC 器容
功式程用應後之,作工定設態組的碎瑣時發開期初化簡以,能功的定綁動
。 係 關 賴依的 間 件 物 與 件 物 定 設的楚 清 就 , 後 之 定 確 能
3.2.4 集合物件
在,件物合集等 、
j ava.util.List 、 、列陣於對
j ava.util.Set j ava.util.Map
的需所至入注件物合集將再後然,中合集至件物些一入充填須必若前入注
並 ,件物 合 集 成 生 或 護 維 動 自 來 器 容 的
Bean Spring 由交以可也,時
IoC
。入注賴依成完
定別類 個 有若如 例 , 範 示 作 式 程 用應的 整 完 個 舉 接 直 邊 這 SomeBean
:下如義
CollectionDemo SomeBean.java
package onlyfun.caterpillar;
import java.util.List;
import java.util.Map;
public class SomeBean {
private String[] someStrArray;
private Some[] someObjArray;
private List someList;
private Map someMap;
public String[] getSomeStrArray() {
return someStrArray;
}
public void setSomeStrArray(String[] someStrArray) {
this.someStrArray = someStrArray;
}
public Some[] getSomeObjArray() {
return someObjArray;
}
3 33
- 34. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
public void setSomeObjArray(Some[] someObjArray) {
this.someObjArray = someObjArray;
}
public List getSomeList() {
return someList;
}
public void setSomeList(List someList) {
this.someList = someList;
}
public Map getSomeMap() {
return someMap;
}
public void setSomeMap(Map someMap) {
this.someMap = someMap;
}
}
與 、列 陣 些 一 義 定 的 單 簡 是 只 中 別 類
SomeBean 在 L ist Map 稍,性 屬
在,入注成生來 由 將 件 物依相 的 需 所 性 屬 些 這 後
Spring SomeBean 使還中
Some :下如容內其,別類 到用
CollectionDemo Some.java
package onlyfun.caterpillar;
public class Some {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
3 34
- 35. Chapter 3 IoC 器容
public String toString() {
return name;
}
}
用 使 是 時 檔 義 定寫撰 在 , 入 注 係 關 賴 依 的 態 型 或 列 陣 於 對
List <list>
的它其至考參來 用使是或,串字定指籤標
<value> 用使並,籤標<ref>
,籤標
Bean 用 使 是則入 注 係 關 賴 依 的 態 型 於 對 ; 例 實
Map <map> M ap
用使後然, 定指籤標
key-value 用要您以所,
<entry> 定指須必
key <value>
。例實 的它其至考參來 <ref> 用使是 或 , 串 字 定 指 籤 標
Bean
:下如寫撰義定
CollectionDemo 的案專
beans-config.xml
CollectionDemo beans-config.xml
<?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-2.0.xsd">
<bean id="some1" class="onlyfun.caterpillar.Some">
<property name="name" value="Justin"/>
</bean>
<bean id="some2" class="onlyfun.caterpillar.Some">
<property name="name" value="momor"/>
</bean>
<bean id="someBean" class="onlyfun.caterpillar.SomeBean">
<property name="someStrArray">
<list>
<value>Hello</value>
<value>Welcome</value>
</list>
</property>
3 3
- 36. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
<property name="someObjArray">
<list>
<ref bean="some1"/>
<ref bean="some2"/>
</list>
</property>
<property name="someList">
<list>
<value>ListTest</value>
<ref bean="some1"/>
<ref bean="some2"/>
</list>
</property>
<property name="someMap">
<map>
<entry key="MapTest">
<value>Hello!Justin!</value>
</entry>
<entry key="someKey1">
<ref bean="some1"/>
</entry>
</map>
</property>
</bean>
</beans>
您,立建的期預如否是係關賴依及以,確正否是寫撰檔義定試測了為
: 式 程 試測的 下 如 個 一 寫 撰 以 可
CollectionDemo SpringDemo.java
package onlyfun.caterpillar;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
3 36
- 37. Chapter 3 IoC 器容
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(
"beans-config.xml");
SomeBean someBean =
(SomeBean) context.getBean("someBean");
//件物入注賴依態型列陣得取
String[] strs =
(String[]) someBean.getSomeStrArray();
Some[] somes =
(Some[]) someBean.getSomeObjArray();
for(int i = 0; i < strs.length; i++) {
System.out.println(strs[i] + ","
+ somes[i].getName());
}
//得取 List件物入注賴依態型
System.out.println();
List someList = (List) someBean.getSomeList();
for(int i = 0; i < someList.size(); i++) {
System.out.println(someList.get(i));
}
//得取 Map件物入注賴依態型
System.out.println();
Map someMap = (Map) someBean.getSomeMap();
System.out.println(someMap.get("MapTest"));
System.out.println(someMap.get("someKey1"));
}
}
:示 所 下 如 果 結 的 行 執
3 37
- 38. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
圖 3.5 CollectionDemo 果結行執案專
定設在 Map ,時入注 < entry> :式形的下以本原,上定設的籤標
<entry key="MapTest">
<value>Hello!Justin!</value>
</entry>
:為寫撰以可還
<entry key="MapTest" value="Hello!Justin!"/>
果如 key-value 個某至考參要別分 Bean 方的下以為寫撰以可則,例實
:式
<entry>
<key>
<ref bean="myKeyBean"/>
</key>
<ref bean="myValueBean"/>
</entry>
: 潔簡為 更 上 寫 撰 在 , 式 型的下 以 為 寫 撰 以 可 還 您
<entry key-ref="myKeyBean" value-ref="myValueBean"/>
會許 也,時 件 物 合 集 義 定 在,本 版 的 上 以 是 的 用 使 所 您 果 如
JDK 5.0
: 如 例 , 態 型 的 放 存所件 物 合 集 義 定 來 能 功 的 )
G eneric (型泛用使
3 38
- 39. Chapter 3 IoC 器容
public class Some {
private Map<String, Float> somes;
public void setSomes(Map<String, Float> somes) {
this.somes = somes;
}
}
,時 入 注 賴 依 行 進 在 則 S pring 將再,作動的換轉態型作性屬為試嘗會
: 如 例,中 之 件 物 合 集 入 放 之
...
<bean id="some" class="onlyfun.caterpillar.Some">
<property name="somes">
<map>
<entry key="Justin" value="99.99"/>
<entry key="momor" value="99.75"/>
</map>
</property>
</bean>
...
將會 ,下之定設的樣這在 S pring key , 為換轉值的
String v alue 定設的
中別類 合符以, 為換轉
Float Some somes 。告宣型泛的性屬
是的入注要果如 java.util.Set 用使則,話的態型 <set> 設個一,籤標
:示所下如段片的定
...
<set>
<value>a set element</value>
<ref bean="otherBean"/>
<ref bean="anotherBean"/>
</set>
...
的入注要若java.util.Properties 用使則,態型 < props> 與 < prop> ,籤 標
Bean :下如範示法寫的檔義定
3 3
- 40. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
<bean id=....>
....
<property name="someProperties">
<props>
<prop key="someProkey1">someProValue1</prop>
<prop key="someProkey2">someProValue2</prop>
</props>
</property>
</bean>
定設件物合集為慮考要則,件物個一入注只不件物合集的您果如 " id"
用使要則,件物 是若如例,稱名
List org.springframework.beans.factory.
:示所下如,義定來
config.ListFactoryBean
<bean id="emails"
class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<value>justin@caterpillar.onlyfun</value>
<value>momor@caterpillar.onlyfun</value>
</list>
</property>
</bean>
是果如 Map :定設下如以可則,件物
<bean id="emails"
class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map>
<entry key="justin" value="justin@caterpillar.onlyfun"/>
<entry key="momor" value="momor@caterpillar.onlyfun"/>
</map>
</property>
</bean>
:定設下如以可則,件物 是果如
Set
<bean id="emails"
class="org.springframework.beans.factory.config.SetFactoryBean">
3 4
- 41. Chapter 3 IoC 器容
<property name="sourceSet">
<set>
<value>justin@caterpillar.onlyfun</value>
<value>momor@caterpillar.onlyfun</value>
</set>
</property>
</bean>
是果如 P roperties 用使以可則,態型 o rg.springframework.beans.factory.
:如例,
config.PropertiesFactoryBean
<bean id="propConfiguration"
class="org.springframework.beans.
factory.config.PropertiesFactoryBean">
→
<props>
<prop key="someProkey1">someProValue1</prop>
<prop key="someProkey2">someProValue2</prop>
</props>
</bean>
用使 是 或 "location" 定指,性屬 .properties 取讀中從,置位的案檔 Properties
:如例,料資
<bean id="businessConfig"
class="org.springframework.beans.
→ factory.config.PropertiesFactoryBean">
<property name="location"
value="classpath:onlyfun/caterpillar/config.properties"/>
</bean>
與這, 併 合 的 件 物 合 集 援 支 還 , 中
Spring 2.0 在 3.1.6 的到談 Bean 定
:如 例 , 似 類 承 繼 之 義
<bean id="parent" abstract="true" class="onlyfun.caterpillar.Some">
<property name="someProperties">
<props>
<prop key="someProkey1">someProValue1</prop>
<prop key="someProkey2">someProValue2</prop>
</props>
</property>
3 41
- 42. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
</bean>
<bean id="child" parent="parent">
<property name="someProperties">
<props merge="true">
<prop key="someProkey2">otherProValue2</prop>
<prop key="someProkey3">someProValue3</prop>
</props>
</property>
</bean>
為性屬 了定設 的中
" child" 到意注
< props> " merge" " true" 定設的上以,
義定新重,義定的中 承繼會將,
" child" 的得取所 " parent" " someProKey2"
為 增新並,
" otherProValue2" 為" someProKey3" " someProValue3" 是就也,
:案檔 的下 以 義 定 於 當 相 後 最
. properties
someProKey1=someProValue1
someProKey2=otherProValue2
someProKey3=someProValue3
3.2.5 Spring 2.0 的<util>標籤
可則,定設檔義定 的 於基用使若中
Spring 2.0 在 XML Schema XML
省便方為更時義定 定設在籤標 。充擴籤標 的增新入加以
< util> < util> Bean
在須必,籤標 用使要,助幫的大很有化簡的檔定設
XML 於對,事 < util>
XML :) (間空稱名 入加中
util n amespace
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
...
</beans>
3 42
- 43. Chapter 3 IoC 器容
用使別分以可,化簡的上定設件物合集於籤標 紹介來先首
< util>
先代取來,籤標等
<util:list> 、 、
< util:map> 、 < util:set> < util:properties>
與 、 、 的紹介所前
ListFactoryBean MapFactoryBean SetFactoryBean
其將以可,例為案專 以先邊這。
PropertiesFactoryBean CollectionDemo
XML :容內的下以為換更檔定設
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="some1" class="onlyfun.caterpillar.Some">
<property name="name" value="Justin"/>
</bean>
<bean id="some2" class="onlyfun.caterpillar.Some">
<property name="name" value="momor"/>
</bean>
<util:list id="strArray">
<value>Hello</value>
<value>Welcome</value>
</util:list>
<util:list id="objArray">
<ref bean="some1"/>
<ref bean="some2"/>
</util:list>
<util:list id="list" list-class="java.util.ArrayList">
<value>ListTest</value>
<ref bean="some1"/>
<ref bean="some2"/>
</util:list>
3 43
- 44. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
<util:map id="map" map-class="java.util.HashMap">
<entry key="MapTest" value="Hello!Justin!"/>
<entry key="someKey1" value-ref="some1"/>
</util:map>
<bean id="someBean" class="onlyfun.caterpillar.SomeBean">
<property name="someStrArray" ref="strArray"/>
<property name="someObjArray" ref="objArray"/>
<property name="someList" ref="list"/>
<property name="someMap" ref="map"/>
</bean>
</beans>
若,件物合集的用使要所定指以可性屬 、
" list-class" 中其
" map-class"
籤標 是下以。件物器容的作實定決行自器容由則,定指不 < util:properties>
:例範用使的
<util:properties id="businessConfig"
location="classpath:onlyfun/caterpillar/cpnfig.properties"/>
是下以 < util:set> ,的樣同,例範用使的 " set-class" 物合集定指來用可
:態型的用使所件
<util:set id="emails" set-class="java.util.TreeSet">
<value>justin@caterpillar.onlyfun</value>
<value>momor@caterpillar.onlyfun</value>
</util:set>
有還,外之籤標 的紹介所邊這了除 < util> < util:constant> 靜定設來用可
定設於免而,) (員成料資態
s tatic field org.springframework.beans.factory.
:如例,
config.FieldRetrievingFactoryBean
<bean id="..." class="...">
<property name="someProperty">
<util:constant
static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
</property>
</bean>
3 44
- 45. Chapter 3 IoC 器容
個某為以可,籤標 用使以可還
< util:property-path> Bean 設員成性屬的
定設於免以,中之理管器容於可之使,稱名 定
" id" org.springframework.
:如例,
beans.factory.config.PropertyPathFactoryBean
<bean id="someBean" class="onlyfun.caterpillar.SomeBean">
<property name="name" value="guest"/>
</bean>
<!—id name
為 Bean
的 是會將值其, someBean.name-->
<util:property-path id="name" path="someBean.name"/>
3.2.6 Lookup Method Injection
個一計設要在現設假 Singleton 的 叫 呼 當,
MessageManager display()
的 立 建 新 統系個 一 得 取 會 , 時 法 方 Message :如 例 , 示 顯 以 加 並 件 物
LookupMethodInjectionDemo MessageManager.java
package onlyfun.caterpillar;
public abstract class MessageManager {
public void display() {
Message message = createMessage();
System.out.println(message);
}
protected abstract Message createMessage();
}
集 收 的 單 簡 只 則 例 範 的邊 這 在 , 訊 資 關 相 的 時 當 統 系 了 集 收
Message
:訊資間時的統系
3 4
- 46. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
LookupMethodInjectionDemo Message.java
package onlyfun.caterpillar;
import java.util.Date;
public class Message {
private String sysMessage;
public Message() {
sysMessage = " :訊資統系 " + new Date().toString();
}
public String toString() {
return sysMessage;
}
}
個一 之使,法方 作實接直式程寫撰想不邊這在 createMessage() new
的件物
Message 入注並生產來 過透望希而,回傳並件物 Spring Message
將,中檔定設 在的純單。性彈的 換抽在得獲以,話
Message XML Message
過透在有只,定設麼這為因,的通不行是
" scope" 定設性屬 的
" prototype"
會才,時 得取來
BeanFactory 的 或
ApplicationContext getBean() Message
。
Message 個一化例實新重
用使, 的 用使以可時這
Spring Lookup Method Injection < lookup-
,入注行進並件物的新生產,法方的 個某用使定指可,籤標
method> Bean
XML :寫撰麼這以可,中檔定設 在如例
LookupMethodInjectionDemo beans-config.xml
<?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
3 46
- 47. Chapter 3 IoC 器容
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="sysMessage"
class="onlyfun.caterpillar.Message" scope="prototype"/>
<bean id="messageManager"
class="onlyfun.caterpillar.MessageManager">
<lookup-method name="createMessage" bean="sysMessage"/>
</bean>
</beans>
子的 個一生產 用使將
S pring ,下之定設麼這 CGLIB MessageManager
呼次每在且並,)中之 入加 的 將要 以 所 ( 作 實 別 類
CGLIB . jar Classpath
一用使以可,回傳並件物 個一立建,時法方
createMessage() 到叫
Message
: 果 結 行執範 示 來 式 程 的 單 簡 個
LookupMethodInjectionDemo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext(
"beans-config.xml");
MessageManager messageManager =
(MessageManager) context.getBean("messageManager");
try {
messageManager.display();
Thread.sleep(1000);
messageManager.display();
Thread.sleep(1000);
messageManager.display();
} catch (InterruptedException e) {
e.printStackTrace();
}
3 47
- 48. 3 48
。 明說與例範關 相的
3 .3.8.2. Arbitrary method replacement
,中當件 文考 參 考參接直 以可 Spring
,趣興有若。件物的來原改修用不而,作實法方的件物個某代取的步一進更
以可 , Arbitrary method replacement
的用 常不更個 一供提還 中 Spring
。中之 MessageManager 入注件物 Message
的定指將,作實供提 Spring
由, createMessage() 法 方 定 指 以 可 它,到 看 以 可 中 子 例 的 際 實 從,一 之 案
方決解 Method Injection 的供提所 Spring
是 Lookup Method Injection
果結行執案專 3.6 LookupMethodInjectionDemo 圖
:件物 Message
的新生 產 都 次 每 實 確 到 看
,中果 結 的 行 執 從 以 可 , 生 產 新 重 實 確 否 是 件 物 Message
察觀以,訊資間
時的統系隔區,秒毫 1000
停暫間之 display()
叫呼 次 每 在 意 故 中 式 程
}
}
) – http://openhome.cc 良信林(冊手術技 Spring 2.0
- 49. Chapter 3 IoC 器容
3.3 Bean 進階管理
到識意要需不件組些這是況情的好最,說來件組式程用應於對上想理
可 您 而 然, 關 相 的
Spring 到 用 使 不 是 就 說 來 體 具,在 存 的 器 容 Spring API
於關有知得式程些這讓,式程務服 些一寫撰件組式程用應為以
Spring
您,面方一另。能功些一的供提所
Spring 得 獲 以,息 訊 些 一 的 器 容
Spring
進些一供提節小個這,理處外額些一行進件組式程用應對器容讓須必能可
Bean 。式方的理管與定設 的階
3.3.1 非 XML 定義檔的組態方式
,檔義定為作 用使都式程範示 Spring 個每的到見所前先在 XML X ML
(案專碼始原放開的多許此因也,定設態組於用適式格層階的案檔 O pen
非 供提會 也 常 通 但 , 式 方 義 定 態 組 的 設 預 為 作
source project XML 將都)
XML ,式方定設的 案檔性屬供提如例,式方的檔義定 .properties S pring
。 義定
.properties 案檔性屬用使以可也
Bean
:別類 個 一 了 義 定 您 設 假,說 來 子 例 的 際 實 個 舉
HelloBean
PropertiesDemo HelloBean.java
package onlyfun.caterpillar;
public class HelloBean {
private String helloWord;
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
3 4
- 50. Spring 2.0 良信林(冊手術技 – http://openhome.cc )
}
個一寫撰改邊這在 beans-config.properties 義定來 Bean 等入注 賴 依 與
:容內
PropertiesDemo beans-config.properties
helloBean.(class)=onlyfun.caterpillar.HelloBean
helloBean.helloWord=Welcome
定指於用 ,定設名別的 是即稱名"helloBean" 中檔性屬 Bean . (class)
有還如例,定設性屬的需所檔義定 示表號括有,源來別類
Bean
其於至,定設以可等
. (abstract)、 、
. (parent) 、 如
. (lazy-init) . (singleton)
考參要果如,稱名性屬的 為即 如例,式方定設性屬的它
" .helloWord" Bean
用使以可。
Bean 用使則, 的在存已
" .helloWorld(ref)" org.springframework.
讀,檔性屬取讀來
beans.factory.support.PropertiesBeanDefinitionReader
:下 如 式 程 範 示 之 義 定 的 中 案 檔
.properties 取
PropertiesDemo SpringDemo.java
package onlyfun.caterpillar;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.
support.BeanDefinitionRegistry;
import org.springframework.beans.factory.
support.DefaultListableBeanFactory;
import org.springframework.beans.factory.
support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
public class SpringDemo {
public static void main(String[] args) {
BeanDefinitionRegistry reg =
new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader =
new PropertiesBeanDefinitionReader(reg);
3
- 51. Chapter 3 IoC 器容
reader.loadBeanDefinitions(
new ClassPathResource(
"beans-config.properties"));
BeanFactory factory = (BeanFactory) reg;
HelloBean hello =
(HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
。字文 示顯會果結行執
"Welcome"
定以,式程寫撰接直中式程在以可也,案檔
XML 或 過透了除
.properties
Bean 過透,係關賴依的間之 與 義
Bean org.springframework.beans.Mutable-
給定設別類的 與性屬將,性屬置設
PropertyValues Bean org.springframework.
向並,
beans.factory.support.RootBeanDefinition org.springframework.beans.fac-
。冊註
tory.support.BeanDefinitionRegistry
,的離隔是檔義定與端戶客,是處好的 義定來案檔的何任用使不 Bean
器容的供提所 到用使以可又面方一另,容內的檔義定觸接法無們它 Spring
。能功關相等
:下如寫改別類 的 將以可,子例個看來接直
PropertiesDemo SpringDemo
package onlyfun.caterpillar;
import org.springframework.beans.factory.
support.BeanDefinitionRegistry;
import org.springframework.beans.factory.
support.DefaultListableBeanFactory;
import org.springframework.beans.factory.
support.RootBeanDefinition;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.MutablePropertyValues;
3 1