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、在对应的方法上使用

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

相关推荐
Arva .10 分钟前
讲一下 Spring 中用到的设计模式
java·spring·设计模式
bbq粉刷匠19 分钟前
Java-顺序表
java
dhdjjsjs23 分钟前
Day30 Python Study
开发语言·前端·python
十五年专注C++开发24 分钟前
async_simple:一个轻量级C++异步协程框架
开发语言·网络·c++·boost·asio
Tan_Ying_Y1 小时前
Mybatis的mapper文件中#和$的区别
java·tomcat·mybatis
难以触及的高度1 小时前
Java for循环完全指南:从基础到高性能实践
java·开发语言
wadesir1 小时前
用Python实现ggplot2风格绘图(零基础入门Seaborn与Matplotlib美化技巧)
开发语言·python·matplotlib
sheji34161 小时前
【开题答辩全过程】以 农产品销售系统为例,包含答辩的问题和答案
java·eclipse
油炸自行车1 小时前
【Qt】Qt Creator Debug模式提示“缺少 Windows CDB 调试器配套的扩展组件“”
开发语言·windows·qt
budingxiaomoli1 小时前
多线程(三)
java·开发语言