spring @Transactional注释

use*_*201 5 java spring

我有一个抽象类和两个扩展它的子类.我在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" />
Run Code Online (Sandbox Code Playgroud)

在我的抽象类中,我有以下方法

public void importDataToDB(){
    //all the good stuff goes in here
}

@Transactional
public void executeInsertUpdateQuery(){
    //all the good stuff goes in here
}
Run Code Online (Sandbox Code Playgroud)

我的java代码

ImportConfigFiles importConfigFiles = (ImportConfigFiles)context.getBean("importConfigFile");
importConfigFiles.setFileLocation(destPath);
importConfigFiles.importDataToDB();
Run Code Online (Sandbox Code Playgroud)

这不起作用.executeInsertUpdateQuery()只执行一个本机sql查询.如果我将@Transactional放在imortDataToDB()上它可以工作但是它会使我的事务变得很大,因为在该方法中我循环遍历文件中的所有行并在db中插入记录.

Tom*_*icz 8

这是Spring中的主要缺陷之一 - 如果在同一个类中调用@Transactional来自非事务方法的方法,则会被忽略(除非您使用AspectJ编织).这本身不是Spring问题- EJB具有相同的缺点.@Transactional

不幸的是,基于接口和基于类的代理,你所能做的就是将你的课分成两部分:

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
    }

}
Run Code Online (Sandbox Code Playgroud)

整个喧嚣是由Spring中AOP代理的内部实现引起的.使用上面的代码,每次b.executeInsertUpdateQuery()从非事务处调用时,都会启动新事务BeanA.

我在我的博客上写了一篇关于它的故障:代理,Spring AOP谜语Spring AOP谜语揭秘.