首页 > 编程语言 >springboot 编程事务的封装

springboot 编程事务的封装

时间:2024-09-02 16:27:18浏览次数:4  
标签:事务 封装 springboot Autowired 编程 springframework org import public

一、创建事务管理工具类
java
复制

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
public class TransactionUtils {

    @Autowired
    private PlatformTransactionManager transactionManager;

    public void executeInTransaction(Runnable runnable) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            runnable.run();
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        }
    }
}
这个工具类通过注入PlatformTransactionManager来管理事务。提供了一个executeInTransaction方法,接受一个Runnable参数,在执行这个可运行对象的代码块之前开启事务,若代码块执行成功则提交事务,若出现异常则回滚事务。
二、在业务服务中使用
假设你有一个业务服务类如下:
java
复制
import org.springframework.stereotype.Service;

@Service
public class SomeService {

    public void someBusinessMethod() {
        // 业务逻辑代码
    }
}
三、在控制器或其他地方调用
java
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class SomeController {

    @Autowired
    private TransactionUtils transactionUtils;
    @Autowired
    private SomeService someService;

    public void someAction() {
        transactionUtils.executeInTransaction(() -> {
            someService.someBusinessMethod();
            // 可以继续添加其他业务逻辑,它们都会在同一个事务中执行
        });
    }
}
通过这种方式,将编程式事务的管理封装在一个工具类中,使得在不同的地方使用事务更加方便和统一。同时,也提高了代码的可维护性和可读性,避免了在多个地方重复编写事务管理的代码。

标签:事务,封装,springboot,Autowired,编程,springframework,org,import,public
From: https://www.cnblogs.com/jxkbk/p/18392900

相关文章