You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Pointcut表达式中校验注解值实现切面仅非只读事务生效

解决方案

Spring AOP 原生支持在切点表达式中直接过滤注解属性,不需要通过 JoinPoint 手动解析注解,你可以根据自己的业务场景选择对应写法:

场景1:仅匹配方法上直接标注的非只读事务

如果你的事务注解只会加在方法上,直接修改切点表达式即可:

@AfterReturning("@annotation(org.springframework.transaction.annotation.Transactional(readOnly = false))")
public void afterTransaction() {
    // 原有业务逻辑
}

该写法会自动匹配所有方法上标注了@Transactional且readOnly属性为false的方法,没有显式标注readOnly的事务注解会默认匹配(@Transactional默认readOnly = false)。

场景2:同时匹配类级别+方法级别的非只读事务

如果项目中存在类上标注@Transactional、方法继承类事务属性的情况,用组合切点即可覆盖全部场景:

@AfterReturning("(@within(org.springframework.transaction.annotation.Transactional) || @annotation(org.springframework.transaction.annotation.Transactional)) && !(@within(org.springframework.transaction.annotation.Transactional(readOnly = true)) || @annotation(org.springframework.transaction.annotation.Transactional(readOnly = true)))")
public void afterTransaction() {
    // 原有业务逻辑
}

如果追求更高的可读性,也可以用注解参数绑定的写法:

@AfterReturning("(@within(transactional) || @annotation(transactional)) && transactional.readOnly == false")
public void afterTransaction(org.springframework.transaction.annotation.Transactional transactional) {
    // 原有业务逻辑
}

内容的提问来源于stack exchange,提问作者b.maes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:24:00