标签:
<tx:annotation-driven transaction-manager="transactionManagerX" /> <tx:annotation-driven transaction-manager="transactionManagerY" />
public interface TestEntityService { public void methodX(); public void methodY(); }
public class TestEntityServiceImpl implements TestEntityService { @Resource private TestEntityDao testEntityDao;//实际操作的是datasourceX. @Transactional public void methodX() { testEntityDao.xxx(); testEntityDao.zzz(); } public void methodY() { } }
public class AnotherTestEntityServiceImpl implements TestEntityService { @Resource private TestEntityDao anOtherTestEntityDao;//实际操作的是datasourceY. @Transactional public void methodX() { testEntityDao.mmm(); testEntityDao.nnn(); } public void methodY() { } }
methodX()事务生效测试结果 |
@Transactional
("transactionManagerX")
|
@Transactional
("transactionManagerY")
|
@Transactional
("transactionManagerZ")
transactionManagerZ为未定义过的
|
@Transactional |
TestEntityServiceImpl(实际使用datasourceX) | Y | N | Y | Y |
AnotherTestEntityServiceImpl (实际使用datasourceY) | N | Y | N | N |
<tx:annotation-driven transaction-manager="transactionManagerY" /> <tx:annotation-driven transaction-manager="transactionManagerX" />
methodX()事务生效测试结果 |
@Transactional
("transactionManagerX")
|
@Transactional
("transactionManagerY")
|
@Transactional
("transactionManagerZ")
transactionManagerZ为未定义过的
|
@Transactional |
TestEntityServiceImpl(实际使用datasourceX) | Y | N | N | N |
AnotherTestEntityServiceImpl (实际使用datasourceY) | N | Y | Y | Y |
分析结果(其实源码就可以反应出):容器指定一个默认的事务管理器
建议:实际代码中需要用到@Transactional时,即使默认只有一个transactionManager,@Transactional也将其标明。以提高新增数据源后代码可读性,另外防止定义多个数据源后,以前缺省的不被spring默认为缺省了(比如哪天上线新定义了一个数据源,刚好新定义的transactionManager被先加载了,那就悲剧了。)
<bean id="testEntityService" class="com.xxx.impl.TestEntityServiceImpl"/>
<bean id="testEntityService3" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="transactionManagerX" /> <property name="target"> <bean class="com.xxxx.impl.TestEntityServiceImpl" /> </property> <property name="proxyInterfaces" value="com.xxxx.TestEntityService"/> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean>
public class TestEntityServiceImpl implements TestEntityService { @Resource private TestEntityDao testEntityDao;//实际操作的是datasourceX. @Transactional public void methodX() { testEntityDao.xxx(); testEntityDao.zzz(); } public void methodY() { methodX() } }
spring的annotation-driven配置事务管理器详解
标签:
原文地址:http://www.cnblogs.com/duanxz/p/4661288.html