java - @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
}
}
}
不想使用自定义注释更改方法签名。
任何设计模式或实现示例都会有很大帮助。谢谢!
解决方案
您可以创建一个保险箱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();
}
}
}
推荐阅读
- pandas - 如何为 Keras LSTM 正确构建 3D 输入
- python - 如何在不使用 .pop() 或 .remove() 的情况下从项目列表中删除特定项目的第一次出现
- javascript - 当从 useEffects 第一次渲染触发时反应弹出 window.open 空开瓶器
- go - 如何在 Go 和 yaml 包的 API v3 中生成配置文件时对注释进行编码
- java - 如何解决“用户
即使在 InitialContext 中指定了正确的用户,也没有足够的权限访问 EJB' - google-sheets - 从动态单元格引用中提取值
- python - 我怎样才能从字符串中获取特定单词的两个下一个单词?
- macos - 如何修改 MacOS 系统“浮动”屏幕保护程序以一次显示更多图像?
- node.js - 安装节点和 npm 的问题
- r - 从R中的文本构造一个稀疏矩阵