Spring @Transaction方法调用同一个类中的方法,不起作用? [英] Spring @Transaction method call by the method within the same class, does not work?

查看:2157
本文介绍了Spring @Transaction方法调用同一个类中的方法,不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring Transaction的新手。我发现的一些事情很奇怪,可能我确实理解了这一点。我想在方法级别有一个事务处理,并且我在同一个类中有一个调用方法,看起来它不喜欢它,它必须从单独的类调用。我不明白这是怎么可能的。如果有人知道如何解决这个问题,我将不胜感激。我想使用相同的类来调用带注释的事务方法。

I am new to Spring Transaction. Some thing that I found really odd, probably I did understand this properly. I wanted to have a transactional around method level and I have a caller method within the same class and it seems like it does not like that, it has to be called from the separate class. I don't understand how is that possible. If anyone has an idea how to resolve this issue, I would greatly appreciate. I would like to use the same class to call the annotated transactional method.

这是代码:

public class UserService {

    @Transactional
    public boolean addUser(String userName, String password) {
        try {
            // call DAO layer and adds to database.
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();

        }
    }

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            addUser(user.getUserName, user.getPassword);
        }
    } 
}


推荐答案

Spring AOP (动态对象和 cglib )。

It's a limitation of Spring AOP (dynamic objects and cglib).

如果您将Spring配置为使用 AspectJ 来处理事务,那么您的代码将起作用。

If you configure Spring to use AspectJ to handle the transactions, your code will work.

简单且可能最好的选择是重构代码。例如,一个处理用户的类和一个处理每个用户的类。然后使用Spring AOP的默认事务处理将起作用。

The simple and probably best alternative is to refactor your code. For example one class that handles users and one that process each user. Then default transaction handling with Spring AOP will work.

要使Spring能够使用AspectJ进行交易,您必须将模式设置为AspectJ:

To enable Spring to use AspectJ for transactions, you must set the mode to AspectJ:

<tx:annotation-driven mode="aspectj"/>

如果你使用的是旧版本超过3.0的Spring,你还必须将它添加到你的Spring配置:

If you're using Spring with an older version than 3.0, you must also add this to your Spring configuration:

<bean class="org.springframework.transaction.aspectj
        .AnnotationTransactionAspect" factory-method="aspectOf">
    <property name="transactionManager" ref="transactionManager" />
</bean>

这篇关于Spring @Transaction方法调用同一个类中的方法,不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆