对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

简洁的代理定义

特别是在定义事务代理时,你可能会遇到许多类似的代理定义。使用父级和子级bean定义,以及内部bean定义,可以导致更干净和更简洁的代理定义。spring-doc.cadn.net.cn

首先,我们为代理创建一个父级、模板、bean定义,如下:spring-doc.cadn.net.cn

<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:spring-doc.cadn.net.cn

<bean id="myService" parent="txProxyTemplate">
	<property name="target">
		<bean class="org.springframework.samples.MyServiceImpl">
		</bean>
	</property>
</bean>

您可以从父模板中覆盖属性。在下面的例子中,我们覆盖了事务传播设置:spring-doc.cadn.net.cn

<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示例中,我们明确将父bean定义标记为抽象的,方法是将abstract属性设置为true,如先前所述,以便它实际上可能永远不会被实例化。应用程序上下文(但不是简单的bean工厂)默认情况下会预实例化所有单例。因此,重要的是(至少对于单例bean),如果你有一个仅打算用作模板的(父)bean定义,并且此定义指定了一个类,你必须确保将abstract属性设置为true。否则,应用程序上下文实际上会尝试预实例化它。spring-doc.cadn.net.cn