簡潔的代理定義
尤其是在定義事務代理時,您可能會遇到許多相似的代理定義。使用父子 bean 定義以及內部 bean 定義可以使代理定義更加清晰和簡潔。
首先,我們為代理建立一個父級模板 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>
它本身從不例項化,因此它實際上可能是不完整的。然後,每個需要建立的代理都是一個子 bean 定義,它將代理的目標包裝為內部 bean 定義,因為目標無論如何都不會單獨使用。以下示例顯示了這樣一個子 bean:
<bean id="myService" parent="txProxyTemplate">
<property name="target">
<bean class="org.springframework.samples.MyServiceImpl">
</bean>
</property>
</bean>
您可以覆蓋父模板中的屬性。在以下示例中,我們覆蓋了事務傳播設定:
<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>
請注意,在父 bean 示例中,我們透過將 abstract 屬性設定為 true,如之前所述,明確將父 bean 定義標記為抽象,以便它實際上可能永遠不會被例項化。應用程式上下文(但不是簡單的 bean 工廠)預設預例項化所有單例。因此,重要的是(至少對於單例 bean),如果您有一個(父)bean 定義,您打算僅用作模板,並且此定義指定了一個類,則必須確保將 abstract 屬性設定為 true。否則,應用程式上下文實際上會嘗試預例項化它。