java - @Around注解: Make variable available to joinpoint without changing method signature and use it later

标签 java spring spring-boot spring-annotations aspect

同时使用@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
        }
    }
}

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

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

最佳答案

您可以创建一个安全的 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();
    }

}

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

@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();

        }
    }
}

关于java - @Around注解: Make variable available to joinpoint without changing method signature and use it later,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57714961/

相关文章:

java - 提交后如何从服务器插件中的 Neo4j 数据库获取属性?

Java Bean : Overglorified Associative Arrays?

java - Spring Boot 退出代码生成器 - 实现不起作用

java - 为什么术语 "unit of work"如此重要,为什么 JDBC AutoCommit 违反了这个模式?

java - JPARepository 中 Long 的含义?

spring - 在 tomcat 上部署 Togglz Spring Boot 时出错

java - android COuntDownTimer 停止并启动新的计时器

java - 无法匹配 Mongodb 中的模式搜索

java - 有没有办法在连接到 Active MQ 队列时让 Spring JMS 监听器有初始延迟?

spring-boot - 基于微服务的环境中的 Keycloak 身份验证流程