简洁的代理定义

尤其是在定义事务代理时,您可能会遇到许多相似的代理定义。使用父子 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。否则,应用程序上下文实际上会尝试预实例化它。

© . This site is unofficial and not affiliated with VMware.