【发布时间】:2015-07-03 09:38:34
【问题描述】:
我想从我的 Spring @Configuration 类中配置“事务性”bean,而不是使用 @Transactional 注释类实现本身。
有点像老派的方式,从 XML 文件配置事务建议,但不需要对我的类/方法名称的字符串引用来创建切入点。
原因是bean实现在另一个代码库中,它所属的模块不依赖于Spring。阅读:我没有接触那个 bean 的源代码,只是实例化它。该类是最终类,也不能对其进行扩展以向子类添加 Spring 注释。 为简单起见,假设所有方法都必须是事务性的。
bean 实现:
/** This class has no Spring dependency... */
// @Transactional <- which means I can't use this here
public final class ComplexComponentImpl implements ComplexComponent {
private SomeRepository repo;
public ComplexComponentImpl(SomeRepository repository) { this.repo = repository }
public void saveEntities(SomeEntity e1, SomeEntity e2) {
repo.save(e1);
throw new IllegalStateException("Make the transaction fail");
}
我想在我的配置类中做什么(在我的单元测试中不起作用):
@Configuration
@EnableTransactionManagement
public class ComplexComponentConfig {
@Bean
@Transactional // <- Make the bean transactional here
public ComplexComponent complexComponent() {
return new ComplexComponentImpl(repository());
}
// ...
}
确实,上面的示例不起作用,因为在运行时没有任何“事务性”:实体e1 被持久化,即使抛出异常。
请注意,我的事务管理设置与标有@Transactional 的实现类完美配合。
问题:是否可以从 @Configuration 类中声明 @Beans 事务性,或者考虑到上述约束是否有任何替代方法?
【问题讨论】:
标签: java spring jpa transactions