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

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

相关推荐
梦里不知身是客114 分钟前
tomcat作用和功能以及默认端口号
java·tomcat
喵了meme8 分钟前
C语言实战3
c语言·开发语言
码界奇点9 分钟前
基于SpringBoot与Vue3的多租户中后台管理系统设计与实现
java·spring boot·后端·spring·车载系统·毕业设计·源代码管理
Cigaretter712 分钟前
Day 31 类的装饰器
开发语言·python
长安城没有风12 分钟前
在 IntelliJ IDEA 中高效使用 Git 的实用指南
java·git·intellij-idea
Code blocks12 分钟前
SpringBoot从0-1集成Netty实现自定义协议开发
java·spring boot·后端
DsirNg13 分钟前
JavaScript 事件循环机制详解及项目中的应用
开发语言·javascript·ecmascript
武子康18 分钟前
Java-195 RabbitMQ BlockingQueue 手搓“消息中间件”雏形:生产者-消费者模型到企业级 MQ 差在哪
java·分布式·架构·消息队列·rabbitmq·java-rabbitmq·mq
Propeller18 分钟前
【Android】动态操作 Window 的背后机制
android·java
研☆香19 分钟前
深入解析JavaScript的arguments对象
开发语言·前端·javascript