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