我有一个抽象类和两个扩展它的子类。我在 spring 配置文件中有以下内容
<bean id="importConfigFile" class="xxx.ImportConfigFiles" parent="parentImportFile"></bean>
<bean id="importFile" class="xxx.ImportUMTSKPIFiles" parent="parentImportFile"></bean>
<bean id="parentImportFile" name="parentImportFile" class="xxx.ImportUMTSFiles" abstract="true"></bean>
<tx:annotation-driven transaction-manager="transactionManager" />
在我的抽象类中,我有以下方法
public void importDataToDB(){
//all the good stuff goes in here
}
@Transactional
public void executeInsertUpdateQuery(){
//all the good stuff goes in here
}
我的java代码
ImportConfigFiles importConfigFiles = (ImportConfigFiles)context.getBean("importConfigFile");
importConfigFiles.setFileLocation(destPath);
importConfigFiles.importDataToDB();
这是行不通的。 executeInsertUpdateQuery() 仅执行一个本机 SQL 查询。如果我将 @Transactional 放在 imortDataToDB() 上,它会起作用,但它会使我的事务变得巨大,因为在该方法中,我循环遍历文件中的所有行并将记录插入数据库中。
这是 Spring 的主要陷阱之一 - 如果你打电话@Transactional
-非事务方法的方法在同一个班, the @Transactional
被忽略(除非您使用 AspectJ 编织)。这不是Spring的问题per se- EJB也有同样的缺点。
不幸的是,对于基于接口和基于类的代理,您所能做的就是将您的类分成两部分:
public class BeanA() {
@Resource
private BeanB b;
public void importDataToDB(){
b.executeInsertUpdateQuery();
}
}
public class BeanB {
@Transactional
public void executeInsertUpdateQuery(){
//all the good stuff goes in here
}
}
整个混乱是由 Spring 中 AOP 代理的内部实现引起的。使用上面的代码,每次您致电时都会启动新交易b.executeInsertUpdateQuery()
来自非交易性BeanA
.
I wrote about it on my blog Spring pitfalls: proxying http://nurkiewicz.blogspot.com/2011/10/spring-pitfalls-proxying.html, Spring AOP riddle http://nurkiewicz.blogspot.com/2009/08/spring-aop-riddle.html and Spring AOP riddle demystified http://nurkiewicz.blogspot.com/2009/09/spring-aop-riddle-demystified.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)