springBoot事务切面Aop

本文详细介绍了如何使用Spring框架进行事务管理配置,并结合AOP实现对指定服务层方法的事务控制。通过具体代码展示了如何自定义TransactionInterceptor,设置不同方法的事务属性,以及如何创建Advisor来匹配特定的表达式。


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;

@Aspect
@Configuration
public class TransConfig {
    private static final Logger logger = LoggerFactory.getLogger(TransConfig.class);
    private static final int AOP_TIME_OUT = 50000;
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com..*.service..*.*(..))";
    @Autowired
    private PlatformTransactionManager transactionManager;

    public TransConfig() {
    }

    @Bean
    public TransactionInterceptor txAdvice() {
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(0);
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        requiredTx.setPropagationBehavior(0);
        requiredTx.setTimeout(50000);
        Map<String, TransactionAttribute> methodMap = new HashMap();
        methodMap.put("tx*", requiredTx);
        source.setNameMap(methodMap);
        TransactionInterceptor txAdvice = new TransactionInterceptor(this.transactionManager, source);
        return txAdvice;
    }

    @Bean(
        name = {"txAdviceAdvisor"}
    )
    public Advisor txAdviceAdvisor() {
        logger.info("===============================创建txAdviceAdvisor===================================");
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com..*.service..*.*(..))");
        return new DefaultPointcutAdvisor(pointcut, this.txAdvice());
    }
}
### Spring Boot 中 AOP(面向切面编程)的实现与使用 #### 一、什么是AOPAOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,旨在通过分离横切关注点(cross-cutting concerns),从而提升代码的模块化程度。在实际开发中,诸如日志记录、事务管理等功能通常会贯穿多个业务逻辑模块,这些功能被称为横切关注点[^1]。 #### 二、Spring Boot 中配置和使用 AOP 以下是关于如何在 Spring Boot 中实现 AOP 的具体说明: #### (1)引入依赖 要在项目中启用 AOP 功能,需在 `pom.xml` 文件中添加如下 Maven 依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 此依赖包含了必要的库文件以支持 AOP 功能[^2]。 #### (2)定义切面类 创建一个标注有 `@Aspect` 和 `@Component` 注解的类作为切面类。该类用于封装横切逻辑。例如: ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") // 定义切入点 public void logBefore() { System.out.println("Method is about to execute..."); } } ``` 上述代码片段展示了如何利用 AspectJ 表达式语法指定切入点,并在目标方法执行前打印一条日志消息[^3]。 #### (3)运行机制解析 当应用程序启动时,Spring 将扫描所有带有 `@Aspect` 注解的 Bean 并将其注册为切面。随后,在匹配到相应的连接点时自动应用所定义的通知行为。这种动态代理技术使得无需修改原有业务代码即可注入额外的功能逻辑[^4]。 --- ### 示例总结 综上所述,借助于 Spring Boot 提供的一系列便捷工具以及强大的 AOP 支持能力,开发者可以轻松实现对系统内重复性工作的集中管理和统一维护工作流的设计模式转换过程中的效率优化等问题解决方案探讨等内容深入研究下去将会更加有助于理解整个架构体系结构背后隐藏着哪些深层次原理及其应用场景分析等方面的知识积累与发展前景展望等方面的思考方向提供帮助和支持服务等工作环节当中去实践探索新的可能性空间范围之内寻找突破口进而推动技术创新进步的步伐不断向前迈进!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值