?
本文檔使用 PHP中文網(wǎng)手冊(cè) 發(fā)布
你也許需要許多相似的代理定義,特別是定義事務(wù)性代理的時(shí)候。使用父子bean定義,以及內(nèi)部bean定義,可以讓代理定義大大得到極大的簡(jiǎn)化。
首先從父bean開(kāi)始,為代理bean創(chuàng)建bean定義模版:
<bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManager"/> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean>
這個(gè)bean本身將永遠(yuǎn)不會(huì)被初始化,所以實(shí)際上是不完整的。而后每個(gè)需要?jiǎng)?chuàng)建的代理都是這個(gè)bean定義的子bean定義,它們把代理的目標(biāo)類(lèi)包裝為一個(gè)內(nèi)部bean定義,因?yàn)槟繕?biāo)對(duì)象本身將不會(huì)被單獨(dú)使用。
<bean id="myService" parent="txProxyTemplate"> <property name="target"> <bean class="org.springframework.samples.MyServiceImpl"> </bean> </property> </bean>
當(dāng)然你可以覆蓋從模版中繼承的屬性,例如在下面這個(gè)例子里的事務(wù)傳播設(shè)置:
<bean id="mySpecialService" parent="txProxyTemplate"> <property name="target"> <bean class="org.springframework.samples.MySpecialServiceImpl"> </bean> </property> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="store*">PROPAGATION_REQUIRED</prop> </props> </property> </bean>
要注意上面例子中我們已經(jīng)明確地通過(guò)設(shè)定abstract屬性把父bean定義標(biāo)注為abstract,在前面的章節(jié)里有描述,這樣它實(shí)際上不能被初始化。 缺省情況下應(yīng)用程序上下文(不僅僅是bean工廠(chǎng))將預(yù)先初始化所有的實(shí)例為單例。 因此下面這點(diǎn)是很重要的(至少對(duì)于單例bean來(lái)說(shuō)),如果你有一個(gè)(父)bean定義你希望僅僅作為模版使用,而這個(gè)定義說(shuō)明了一個(gè)類(lèi),你必須把abstract參數(shù)設(shè)置為true,否則應(yīng)用程序上下文將試圖預(yù)先初始化它。