在Spring 4.x一书中,11.5.2 使用原始的TransactionProxyFactoryBean 配置事务,代码如下。
仿照书本代码写一个demo,发现事务并没有回滚。
经过查阅,发现是测试类注入目标业务Bean出错了。配置事务增强后,要使配置生效,调用目标Bean的时候,要注入其代理类。
<bean id="customerService" class="com.gpj.service.CustomerService"
p:customerMapper-ref="customerMapper"/>
<bean id="customerServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
p:target-ref="customerService"
p:transactionManager-ref="txManager">
<property name="transactionAttributes">
<props>
<prop key="testTx">PROPAGATION_REQUIRED,-NullPointerException</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
@Resource(name = "customerServiceProxy")
private CustomerService customerService;
@Test
public void testSpring(){
customerService.testTx();
}
需要实施事务增强的目标业务Bean:CustomerService
为目标业务Bean提供事务增强代理类的id:customerServiceProxy
所以要使用业务Bean的时候,注入Bean要指定name:“customerServiceProxy”