1、 在testcontext下的事务操作
步骤1:继承类:extends AbstractTransactionalJUnit4SpringContextTests
步骤2:申明容器:@ContextConfiguration(locations = { "classpath:normandy/spring/normandy-domain-beans.xml" })
步骤3:申明事物:@TransactionConfiguration(defaultRollback = false)
步骤4:对数据源的事务配置
- <bean name="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <tx:annotation-driven transaction-manager="transactionManager" />
默认情况下, 处于testcontext监控下的类是使用事务操作的。如果某个方法不需要事物,则需要进行显示的说明。
- @Test
- @Transactional(propagation=Propagation.NOT_SUPPORTED, isolation=Isolation.DEFAULT)
- public void testPublish4Length() throws IllegalArgumentException,
- InterruptedException {
- List<ConfigValue> configValues0 = configValueUtil.getAllConfigValue();
- int versionInit0 = 0;
- for (ConfigValue configValue : configValues0) {
- ConfigKey configKey = configValue.getConfigKey();
- if (normandyKey.equals(configKey.getGlobeUid())) {
- versionInit0 = configValue.getVersion();
- }
- }
- System.out.println("==============" + versionInit0);
- try {
- simpleNormandyClient.publish(normandyKey, normandyValue);
- Thread.sleep(2000);
- // 取得version值
- List<ConfigValue> configValues1 = configValueUtil
- .getAllConfigValue();
- int versionInit = 0;
- for (ConfigValue configValue : configValues1) {
- ConfigKey configKey = configValue.getConfigKey();
- if (normandyKey.equals(configKey.getGlobeUid())) {
- versionInit = configValue.getVersion();
- }
- }
- System.out.println("==============" + versionInit);
- simpleNormandyClient.publish(normandyKey, normandyValue);
- Thread.sleep(2000);
- List<ConfigValue> configValues2 = configValueUtil
- .getAllConfigValue();
- int versionLast = 0;
- // 取得version值,version=version+1
- for (ConfigValue configValue : configValues2) {
- ConfigKey configKey = configValue.getConfigKey();
- if (normandyKey.equals(configKey.getGlobeUid())) {
- versionLast = configValue.getVersion();
- }
- }
- System.out.println("==============" + versionLast);
- assertEquals(versionInit + 1, versionLast);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("version检查出错");
- }
- }
测试结果:
- ==============79
- [New I/O client worker #1-1 15/06/11 06:57:33:033 CST] WARN transport.DubboClientTransport: 373 Fire reconnect event of 10.20.136.19:9022.
- ==============80
- ==============81
【注意】
1、默认情况下,遇到运行期例外:回滚数据;非运行期例外:不回滚数据
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/589363,如需转载请自行联系原作者