Spring筆記之七(Types of Injection)
本文研究Spring的三種依賴注入實(shí)現(xiàn)類型——接口注入(Interface Injection)、設(shè)值注入(Setter Injection)、構(gòu)造子注入(Constructor Injection)。
Type1 接口注入: 傳統(tǒng)的創(chuàng)建接口對(duì)象的方法, 借助接口來將調(diào)用者與實(shí)現(xiàn)者分離。如下面的代碼所示:
?2? {
?3?private ?InterfaceB?clzB;
?4?public ?doSomething()?
?5? {
?6?Ojbect?obj?= ?Class.forName(Config.BImplementation).newInstance();
?7?clzB?= ?(InterfaceB)obj;
?8? clzB.doIt();
?9? }
10? ……
11? }
12?
在代碼中創(chuàng)建InterfaceB實(shí)現(xiàn)類的實(shí)例,并將該對(duì)象賦予clzB。也就是依據(jù)Java中的對(duì)象動(dòng)態(tài)多態(tài)技術(shù):
Type2
設(shè)值注入:
在各種類型的依賴注入模式中,設(shè)值注入模式在實(shí)際開發(fā)中得到了最廣泛的應(yīng)用(其中很大一部分得力于Spring框架的
影響)。
?下面為某個(gè)類的示例代碼
?(其中包含有一個(gè)message屬性,該類通過其setMessage()方法獲得右容器所提供的值。)
?2? {
?3???private ?String?message;
?4???public ?String?getMessage()?
?5? ??{
?6?????return ?message;
?7? ??}
?8???public?void ?setMessage(String?string)?
?9? ??{
10?????message?= ?string;
11? ??}
12? }
13?
? 其中message 屬性的值通過配置文件來提供
2??????<property?name="message">
3?????????<value>HeLLo,UpperAction?</value>
4?????</property>
5?</bean>
6?
示例代碼:
配置文件如下
?2?
?3???<constructor-arg>
?4?
?5?<ref?bean="anotherExampleBean"/>
?6?</constructor-arg>
?7???<constructor-arg><ref?bean="yetAnotherBean"/></constructor-arg>
?8???<constructor-arg?type="int">
?9?<value>1</value>
10?</constructor-arg>
11?</bean>
12?<bean?id="anotherExampleBean"?class="examples.AnotherBean"/>
13?<bean?id="yetAnotherBean"?class="examples.YetAnotherBean"/>
14?
ExampleBean代碼:
?2? {
?3?????private ?AnotherBean?beanOne;
?4?????private ?YetAnotherBean?beanTwo;
?5?????private?int ?i;
?6?????public ?ExampleBean(AnotherBean?anotherBean,?YetAnotherBean?yetAnotherBean,
??????????????????????????????????????????????????????????????????? int ?i)?
?7? {
?8?????????this.beanOne?= ?anotherBean;
?9?????????this.beanTwo?= ?yetAnotherBean;
10?????????this.i?= ?i;
11? ????}
12? }
13?
當(dāng)構(gòu)造方法中帶多個(gè)不同的基本數(shù)據(jù)類型的參數(shù)時(shí),為了避免產(chǎn)生二義性,可以采用type或者index來指定構(gòu)造方法的參數(shù)的類型和順序。
如:
?? type方法
2?<value>7500000</value>
3?</constructor-arg>
4???<constructor-arg?type="java.lang.String">
5?<value>42</value>
6?</constructor-arg>
7?
??? index方法
2???<constructor-arg?index="0">
3?<value>7500000</value>
4?</constructor-arg>
5???<constructor-arg?index="1">
6?<value>42</value>
7?</constructor-arg>
8?</bean>
9?
總結(jié):
???? type1在靈活性、易用性上不如其他兩種注入模式, Type2 和Type3型的依賴注入實(shí)現(xiàn)則是目前主流的IOC實(shí)現(xiàn)模式, Type3 和Type2模式各有千秋,而Spring都對(duì)Type3和Type2類型的依賴注入機(jī)制提供了良好支持。 以Type3類型為主,輔之以Type2類型機(jī)制作為補(bǔ)充,可以達(dá)到最好的依賴注入效果,不過對(duì)于基于Spring Framework開發(fā)的應(yīng)用而言,Type2使用更加廣泛。
?
鳳凰涅槃/浴火重生/馬不停蹄/只爭(zhēng)朝夕
???? 隱姓埋名/低調(diào)華麗/簡(jiǎn)單生活/完美人生
posted on 2007-09-26 23:59 poetguo 閱讀(940) 評(píng)論(0) 編輯 收藏 所屬分類: Spring