绕过Spring缓存@Cacheable方法捕获自调用的静态分析工具

如何解决绕过Spring缓存@Cacheable方法捕获自调用的静态分析工具

我知道这是因为在 Spring 中创建代理以处理缓存、事务相关功能的方式。修复它的方法是使用 AspectJ,但我不想走那条路,因为它有自己的问题。 我可以使用任何静态分析工具检测自调用吗?

@Cacheable(value = "defaultCache",key = "#id")
public Person findPerson(int id) {
   return getSession().getPerson(id);
} 

public List<Person> findPersons(int[] ids) {
   List<Person> list = new ArrayList<Person>();
       for (int id : ids) {
      list.add(findPerson(id));
    }
   return list;
} 

解决方法

如果检测内部调用就足够了,您可以使用原生 AspectJ 而不是 Spring AOP,然后在每次发生这种情况时抛出运行时异常或记录警告。这不是静态分析,但总比没有好。另一方面,如果您使用本机 AspectJ,则无论如何您都不受 Spring 代理的限制,方面也适用于自调用。

无论如何,这里是一个方面的样子,包括一个显示它如何工作的 MCVE。我是在 Spring 之外完成的,这就是我使用代理 @Component 注释进行演示的原因。

更新:很抱歉针对 @Component 类而不是 @Cacheable 类/方法,但基本上与我在此处展示的一般方法相同,适用于您的特定情况也是如此,如果您只是稍微调整切入点。

组件注解:

package de.scrum_master.app;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(TYPE)
public @interface Component {}

示例类(组件和非组件):

该组件被其他组件调用不应导致异常/警告:

package de.scrum_master.app;

@Component
public class AnotherComponent {
  public void doSomething() {
    System.out.println("Doing something in another component");
  }
}

这个类不是@Component,所以切面应该忽略它内部的自调用:

package de.scrum_master.app;

public class NotAComponent {
  public void doSomething() {
    System.out.println("Doing something in non-component");
    new AnotherComponent().doSomething();
    internallyCalled("foo");
  }

  public int internallyCalled(String text ) {
    return 11;
  }
}

这个类是一个 @Component。方面应该标记 internallyCalled("foo"),而不是 new AnotherComponent().doSomething()

package de.scrum_master.app;

@Component
public class AComponent {
  public void doSomething() {
    System.out.println("Doing something in component");
    new AnotherComponent().doSomething();
    internallyCalled("foo");
  }

  public int internallyCalled(String text ) {
    return 11;
  }
}

驱动程序应用:

请注意,我在整个示例代码中使用 new 创建组件实例,而不是像在 Spring 中那样从应用程序上下文请求 bean。但是你可以忽略它,这只是一个例子。

package de.scrum_master.app;

public class Application {
  public static void main(String[] args) {
    new NotAComponent().doSomething();
    new AComponent().doSomething();
  }
}

无方面运行时的控制台日志:

Doing something in non-component
Doing something in another component
Doing something in component
Doing something in another component

现在有了切面,而不是最后一条消息,我们期望出现异常或记录警告。操作方法如下:

方面:

抱歉在这里使用原生 AspectJ 语法。当然,您也可以使用基于注解的语法。

package de.scrum_master.aspect;

import de.scrum_master.app.*;

public aspect SelfInvocationInterceptor {
  Object around(Object caller,Object callee) :
    @within(Component) &&
    call(* (@Component *).*(..)) &&
    this(caller) &&
    target(callee)
  {
    if (caller == callee)
      throw new RuntimeException(
        "Self-invocation in component detected from "  + thisEnclosingJoinPointStaticPart.getSignature() +
        " to "+ thisJoinPointStaticPart.getSignature()
      );
    return proceed(caller,callee);
  }
}

使用方面运行时的控制台日志:

Doing something in non-component
Doing something in another component
Doing something in component
Doing something in another component
Exception in thread "main" java.lang.RuntimeException: Self-invocation in component detected from void de.scrum_master.app.AComponent.doSomething() to int de.scrum_master.app.AComponent.internallyCalled(String)
    at de.scrum_master.app.AComponent.internallyCalled_aroundBody3$advice(AComponent.java:8)
    at de.scrum_master.app.AComponent.doSomething(AComponent.java:8)
    at de.scrum_master.app.Application.main(Application.java:6)

我认为,您可以使用这个解决方案,也许宁可记录警告而不是抛出异常,以便温和地指导您的同事检查和改进他们依赖 AOP 的 Spring 组件。有时也许他们无论如何都不希望自调用触发一个方面,这取决于情况。您可以在完整的 AspectJ 模式下运行 Spring 应用程序,然后在评估日志后切换回 Spring AOP。但也许只使用原生 AspectJ 开始并完全避免自调用问题会更简单。


更新:在 AspectJ 中,如果满足某些条件,您还可以使编译器抛出警告或错误。在这种情况下,您只能静态地确定从组件到其他组件的调用,而不能区分自调用和其他组件对其他方法的调用。所以这对你没有帮助。

另请注意,此解决方案仅限于由 @Component 注释的类。如果您的 Spring bean 以其他方式实例化,例如通过 XML 配置或 @Bean 工厂方法,这个简单的方面不起作用。但是可以通过检查被拦截的类是否是代理实例来轻松扩展它,然后才决定标记自调用。不幸的是,您必须将方面代码编织到所有应用程序类中,因为检查只能在运行时进行。

我可以解释更多事情,例如使用自注入并在注入的代理实例上调用内部方法,而不是通过 this.internallyCalled(..)。那么自调用问题也就解决了,这个方法在Spring AOP中也能用。

,

我可以使用任何静态分析工具检测自调用吗?

理论上可以,但要注意 Rice's theorem。任何此类工具有时都会发出错误警报。

您可以使用 abstract interpretation 技术开发这样的工具。您可能需要一年以上的工作。

您可以将此类工具的开发分包给例如Frama-C 团队。然后给我发电子邮件至 basile.starynkevitch@cea.fr

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-