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

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

问题描述

我是 Spring Transaction 的新手.我觉得很奇怪的事情,可能我确实理解正确.

I am new to Spring Transaction. Something 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"/>

如果您使用的 Spring 版本低于 3.0,则还必须将其添加到 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天全站免登陆