Spring @Transactional无效

时间:2014-09-18 10:35:55

标签: java spring transactions spring-transactions

我正在尝试使用带注释的TX Spring支持。

应用程序上下文XML:

<?xml ...>

    <tx:annotation-driven/>

    <bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
        ...
    </bean>

    <bean id="repository" class="Repository">
        <constructor-arg ref="dataSource"/>
    </bean>
</beans>

实际代码:

public class Repository {
    @Transactional
        public void save(Op op) {
            System.out.println("Transaction active:::: " + TransactionSynchronizationManager.isActualTransactionActive());

    ...
    }
}

致电代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/integration-context.xml"})
public class RepositoryTest {
    @Autowired
    private Repository repository;          

    @Test
    public void testRepositoryPersistence() {
        Op op = mock(Op.class);

        repository.save(op);
    }
}

它提供 FALSE。

我做错了什么?

1 个答案:

答案 0 :(得分:7)

您应该在配置中添加它

<context:annotation-config/>

<tx:annotation-driven  transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
</bean>

在RepositoryClass上添加一个接口

public class Repository implements IRepository{
    @Transactional
        public void save(Op op) {
            System.out.println("Transaction active:::: " + TransactionSynchronizationManager.isActualTransactionActive());

    ...
    }
}

这在你的测试类中

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/integration-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class RepositoryTest extends AbstractTransactionalJUnit4SpringContextTests{
    @Autowired
    private IRepository repository;          

    @Test
    public void testRepositoryPersistence() {
        Op op = mock(Op.class);

        repository.save(op);
    }
}

请参阅this教程。