java spring boot 自定义 aop

以一个锁的加锁和释放为例

1、先定义注解

java 复制代码
/**
 * 锁切面
 * @author fmj
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface VersionLockAOP {
}

2、然后定义切面类以及切点

java 复制代码
/**
 * 切面
 */
@Component
@Aspect
@Slf4j
public class VersionLockAOPAspect {
    /**
     * 之前
     * @param joinPoint
     */
    @Before(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
    public void VersionLockAOPBeforePoint(JoinPoint joinPoint) {
        try {
            switch (joinPoint.getSignature().getName()) {
                case "saveVersion":
                    if (!SingleUtil.SINGLE.getReentrantLockSaveVersion().tryLock(2000L, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("saveVersion获取锁失败");
                    }
                    return;
                case "saveVersionHistory":
                    if (!SingleUtil.SINGLE.getReentrantLockSaveUpgrade().tryLock(2000L, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("saveVersionHistory获取锁失败");
                    }
                    return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("获取锁:" + e.getMessage());
        }
    }

    /**
     * 之后
     * @param joinPoint
     */
    @After(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
    public void VersionLockAOPAfterPoint(JoinPoint joinPoint) {
        switch (joinPoint.getSignature().getName()) {
            case "saveVersion":
                if (SingleUtil.SINGLE.getReentrantLockSaveVersion().isLocked()) {
                    SingleUtil.SINGLE.getReentrantLockSaveVersion().unlock();
                }
                return;
            case "saveVersionHistory":
                if(SingleUtil.SINGLE.getReentrantLockSaveUpgrade().isLocked()){
                    SingleUtil.SINGLE.getReentrantLockSaveUpgrade().unlock();
                }
                return;
        }
    }
}

3、在对应的方法上使用

执行该方法前后都会进入切点方法执行对应逻辑

相关推荐
间彧2 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧2 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧2 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng2 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663673 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧3 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方3 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848433 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing3 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员