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

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

相关推荐
一只乔哇噻几秒前
java后端工程师进修ing(研一版 || day41)
java·开发语言·学习·算法
钮钴禄·爱因斯晨10 分钟前
深入剖析LLM:从原理到应用与挑战
开发语言·人工智能
User_芊芊君子18 分钟前
【Java】设计模式——单例、工厂、代理模式
java·设计模式·代理模式
六点半88826 分钟前
【C++】C++11 篇二
开发语言·c++
2301_8035545227 分钟前
正向代理,反向代理,负载均衡还有nginx
java·nginx·负载均衡
要开心吖ZSH29 分钟前
软件设计师备考-(十六)数据结构及算法应用(重要)
java·数据结构·算法·软考·软件设计师
DDDDDDDRDDR33 分钟前
C++容器:list
开发语言·c++·stl
向上的车轮37 分钟前
基于Java Spring Boot的云原生TodoList Demo 项目,验证云原生核心特性
java·spring boot·云原生
Elnaij38 分钟前
从C++开始的编程生活(7)——取地址运算符重载、类型转换、static成员和友元
开发语言·c++
程序员清风39 分钟前
快手一面:为什么要求用Static来修饰ThreadLocal变量?
java·后端·面试