首页 > 解决方案 > @Around 注释:使变量可用于连接点而不更改方法签名并稍后使用

问题描述

在使用 @Around 方面和 Spring 启动时。在 joinPoint 执行之前创建变量的最佳方法是什么,使其在 joinPoint 执行期间可用以收集其中的数据,以及在 joinPoint 执行之后使用在变量中收集的数据?

假设它是一个多线程环境。

@Aspect
@EnableAspectJAutoProxy
public class SomeConfig {

    @Around(value = "@annotation(path.to.my.annotation.here)", argNames = "specificArg")
    public void doLogic(ProceedingJoinPoint joinPoint) throws Throwable {

        //create local variable X for thread execution here
        try{
            joinPoint.proceed(); //or joinPoint.proceed(Object[]);
        }
        finally {
        //use local variable X to do some logic
        }
    }
}

不想使用自定义注释更改方法签名。

任何设计模式或实现示例都会有很大帮助。谢谢!

标签: javaspringspring-bootspring-annotationsaspect

解决方案


您可以创建一个保险箱ThreadLocal并设置您想要的变量,然后再使用它。

public class VariableContext {

    private static ThreadLocal<String> currentVariable = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "";
        }
    };

    public static void setCurrentVariable(String tenant) {
        currentVariable.set(tenant);
    }

    public static String getCurrentVariable() {
        return currentVariable.get();
    }

    public static void clear() {
        currentVariable.remove();
    }

}

在这里您可以使用它或在其他类中使用它。

@Aspect
@EnableAspectJAutoProxy
public class SomeConfig {

    @Around(value = "@annotation(path.to.my.annotation.here)", argNames = "specificArg")
    public void doLogic(ProceedingJoinPoint joinPoint) throws Throwable {

        //create local variable X for thread execution here
        try{
            joinPoint.proceed(); //or joinPoint.proceed(Object[]);
        }
        finally {
        //use local variable X to do some logic
            VariableContext.setCurrentVariable("someValue");
            String result = VariableContext.getCurrentVariable();

        }
    }
}

推荐阅读