简洁的代理定义
尤其是在定义事务代理时,你可能会遇到许多相似的代理定义。使用父子 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 定义旨在仅用作模板,并且此定义指定了一个类,那么确保将 abstract
属性设置为 true
是很重要的(至少对于单例 bean 而言)。否则,应用程序上下文实际上会尝试预实例化它。