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

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

相关推荐
并不喜欢吃鱼9 小时前
从零开始C++----七.继承及相关模型和底层(上篇)
开发语言·c++
沐知全栈开发9 小时前
XML CDATA
开发语言
APIshop9 小时前
Python 爬虫获取闲鱼商品详情 API 接口实战指南
开发语言·爬虫·python
代码羊羊10 小时前
rust-字符串(切片)、元组、结构体、枚举、数组
开发语言·后端·rust
sthnyph10 小时前
TypeScript 与后端开发Node.js
java
逻辑驱动的ken10 小时前
Java高频面试考点场景题08
java·开发语言·面试·求职招聘·春招
不恋水的雨10 小时前
手动调用spring的@Validated校验
java·spring
xxjj998a10 小时前
【Spring】Spring MVC案例
java·spring·mvc
W230357657310 小时前
【改进版】C++ 固定线程池实现:基于调用者运行的拒绝策略优化
开发语言·c++·线程池
阿巴斯甜10 小时前
Android:MagicIndicator的使用
java