使变量可用于连接点而不更改方法签名并稍后使用它

使用 @Around 方面和 Spring boot 时。在 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

        }

    }

}

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


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


繁星淼淼
浏览 108回答 1
1回答

慕妹3242003

您可以创建一个保险箱ThreadLocal并设置所需的变量,然后使用它。public class VariableContext {&nbsp; &nbsp; private static ThreadLocal<String> currentVariable = new ThreadLocal<String>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; protected String initialValue() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; public static void setCurrentVariable(String tenant) {&nbsp; &nbsp; &nbsp; &nbsp; currentVariable.set(tenant);&nbsp; &nbsp; }&nbsp; &nbsp; public static String getCurrentVariable() {&nbsp; &nbsp; &nbsp; &nbsp; return currentVariable.get();&nbsp; &nbsp; }&nbsp; &nbsp; public static void clear() {&nbsp; &nbsp; &nbsp; &nbsp; currentVariable.remove();&nbsp; &nbsp; }}您可以在这里或其他课程中使用它。@Aspect@EnableAspectJAutoProxypublic class SomeConfig {&nbsp; &nbsp; @Around(value = "@annotation(path.to.my.annotation.here)", argNames = "specificArg")&nbsp; &nbsp; public void doLogic(ProceedingJoinPoint joinPoint) throws Throwable {&nbsp; &nbsp; &nbsp; &nbsp; //create local variable X for thread execution here&nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; joinPoint.proceed(); //or joinPoint.proceed(Object[]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; finally {&nbsp; &nbsp; &nbsp; &nbsp; //use local variable X to do some logic&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; VariableContext.setCurrentVariable("someValue");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String result = VariableContext.getCurrentVariable();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java