首页 > Java > java教程 > 正文

如何使用OpenRewrite精准修改带有特定注解的方法参数

DDD
发布: 2025-11-28 13:29:02
原创
543人浏览过

如何使用openrewrite精准修改带有特定注解的方法参数

本文深入探讨了如何利用OpenRewrite框架,针对Java代码中具有特定注解组合(例如`@NotNull`和`@RequestParam`)的方法参数进行精细化改造。我们将介绍声明式和命令式两种配方(Recipe)的实现方式,重点演示如何通过命令式配方结合AST游标(Cursor)机制,实现对代码元素的上下文感知式修改,从而避免常见的`UncaughtVisitorException`,并提供详细的代码示例及测试方法。

OpenRewrite配方:精准修改方法参数注解

OpenRewrite是一个强大的自动化代码重构工具,通过编写配方(Recipe)来识别和修改代码模式。在实际开发中,我们经常需要对代码进行有条件的、细粒度的修改,例如只修改同时带有@NotNull和@RequestParam注解的方法参数,为其@RequestParam注解添加required = true属性。本文将详细介绍如何实现这一目标。

1. 遇到的挑战与问题分析

在尝试对特定代码片段应用OpenRewrite配方时,一个常见的误区是直接在自定义Visitor中调用另一个配方的Visitor。例如,在遍历方法参数时,如果直接在J.VariableDeclarations上调用AddOrUpdateAnnotationAttribute配方的Visitor,可能会遇到org.openrewrite.UncaughtVisitorException: java.lang.IllegalStateException: Expected to find a matching parent for Cursor{Annotation->root}的错误。

这个错误的原因在于,AddOrUpdateAnnotationAttribute配方的Visitor在执行时,期望其上下文(通过Cursor获取)是一个注解(J.Annotation)或其父级是注解。然而,当我们在J.VariableDeclarations的上下文中直接调用它时,Cursor的路径可能不匹配其预期,导致上下文错误。正确的做法是,当我们在遍历到目标注解时,再将修改操作委托给子配方的Visitor,并传递正确的Cursor。

2. 声明式配方(Declarative Recipe):简单但缺乏灵活性

对于简单的、无条件的代码修改,声明式配方是一种快速有效的方法。你可以通过一个YAML文件定义配方,并结合OpenRewrite的构建插件(Maven或Gradle)来应用。

示例:在所有@RequestParam上添加required = true

创建一个名为rewrite.yml的文件:

type: specs.openrewrite.org/v1beta/recipe
name: org.example.MandatoryRequestParameter
displayName: Make Spring `RequestParam` mandatory
description: Add `required` attribute to `RequestParam` and set the value to `true`.
recipeList:
  - org.openrewrite.java.AddOrUpdateAnnotationAttribute:
      annotationType: org.springframework.web.bind.annotation.RequestParam
      attributeName: required
      attributeValue: "true"
登录后复制

集成到Maven项目:

在pom.xml中添加OpenRewrite Maven插件:

<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>4.38.0</version> <!-- 使用最新版本 -->
  <configuration>
    <activeRecipes>
      <recipe>org.example.MandatoryRequestParameter</recipe>
    </activeRecipes>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.openrewrite.recipe</groupId>
      <artifactId>rewrite-spring</artifactId>
      <version>5.3.0</version> <!-- 包含Spring相关配方,可能需要根据实际情况调整 -->
    </dependency>
  </dependencies>
</plugin>
登录后复制

局限性: 这种方式会将required = true应用到所有@RequestParam注解上,无法实现针对特定条件(如同时存在@NotNull)的修改。

摩笔天书
摩笔天书

摩笔天书AI绘本创作平台

摩笔天书 135
查看详情 摩笔天书

3. 命令式配方(Imperative Recipe):实现精细化控制

当需要根据复杂的条件来决定是否应用修改时,命令式配方是更合适的选择。它允许我们通过编写Java代码来遍历抽象语法树(AST),并利用Cursor来获取当前代码元素的上下文信息。

目标: 仅为同时带有@NotNull和@RequestParam注解的方法参数,将其@RequestParam注解的required属性设置为true。

核心思路:

  1. 创建一个主Visitor,继承JavaIsoVisitor。
  2. 重写visitAnnotation方法,因为我们要修改的是注解本身。
  3. 在visitAnnotation中,首先判断当前注解是否为@RequestParam。
  4. 通过getCursor().getParent().getValue()向上导航,获取到当前注解所属的J.VariableDeclarations(即方法参数)。
  5. 检查该J.VariableDeclarations是否同时包含@NotNull注解。
  6. 如果条件满足,则将修改操作委托给AddOrUpdateAnnotationAttribute配方自身的Visitor,并传递当前的Cursor。

实现步骤:

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.AddOrUpdateAnnotationAttribute;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import javax.validation.constraints.NotNull; // 导入此注解以供检查

public class MandatoryRequestParameter extends Recipe {

    private static final String REQUEST_PARAM_FQ_NAME = "org.springframework.web.bind.annotation.RequestParam";
    private static final String NOT_NULL_FQ_NAME = "javax.validation.constraints.NotNull"; // NotNull注解的完全限定名

    @Override
    public @NotNull String getDisplayName() {
        return "Make Spring RequestParam mandatory conditionally";
    }

    @Override
    public String getDescription() {
        return "Adds 'required=true' to @RequestParam annotations on method parameters that also have @NotNull.";
    }

    @Override
    protected TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
        // 优化:只有当源文件引用了RequestParam或NotNull注解时才运行此Visitor
        return new UsesType<>(REQUEST_PARAM_FQ_NAME);
    }

    @Override
    protected @NotNull JavaVisitor<ExecutionContext> getVisitor() {

        // 预先创建AddOrUpdateAnnotationAttribute的Visitor实例
        // 这样可以避免在每次visitAnnotation时都创建新实例
        JavaIsoVisitor addAttributeVisitor = new AddOrUpdateAnnotationAttribute(
                REQUEST_PARAM_FQ_NAME, "required", "true", false
        ).getVisitor();

        return new JavaIsoVisitor<ExecutionContext>() {
            @Override
            public J.Annotation visitAnnotation(J.Annotation annotation, ExecutionContext ctx) {
                J.Annotation a = super.visitAnnotation(annotation, ctx);

                // 1. 检查当前注解是否为 @RequestParam
                if (!TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME)) {
                    return a;
                }

                // 2. 通过Cursor获取其父级,即J.VariableDeclarations(方法参数声明)
                // 确保父级是J.VariableDeclarations类型
                J.VariableDeclarations variableDeclaration = getCursor().getParent(2).getValue(); // 向上两级,Annotation -> J.Annotation.Arguments -> J.VariableDeclarations
                if (variableDeclaration == null) {
                    return a; // 如果无法获取到VariableDeclarations,则返回
                }

                // 3. 检查该方法参数是否同时带有 @NotNull 注解
                boolean hasNotNull = variableDeclaration.getLeadingAnnotations().stream()
                        .anyMatch(ann -> TypeUtils.isOfClassType(ann.getType(), NOT_NULL_FQ_NAME));

                if (hasNotNull) {
                    // 如果条件匹配,则将修改操作委托给预先创建的addAttributeVisitor
                    // 关键在于传递当前的a和ctx以及getCursor(),确保上下文正确
                    return (J.Annotation) addAttributeVisitor.visit(a, ctx, getCursor());
                }
                return a;
            }
        };
    }
}
登录后复制

代码解释:

  • REQUEST_PARAM_FQ_NAME 和 NOT_NULL_FQ_NAME:定义了@RequestParam和@NotNull注解的完全限定名。
  • getSingleSourceApplicableTest():这是一个优化点,UsesType会检查源文件是否引用了指定的类型。如果未引用,则不会运行主Visitor,从而提高性能。
  • addAttributeVisitor:AddOrUpdateAnnotationAttribute配方被实例化一次,并获取其内部的Visitor。
  • visitAnnotation(J.Annotation annotation, ExecutionContext ctx):我们在这里拦截所有注解。
    • TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME):判断当前注解是否为@RequestParam。
    • getCursor().getParent(2).getValue():这是关键一步。getCursor()获取当前AST节点的游标。getParent()方法可以向上导航到父节点。对于一个注解(J.Annotation),它的直接父节点通常是J.Annotation.Arguments(如果注解有参数),再向上才是J.VariableDeclarations。因此,这里使用getParent(2)来获取方法参数声明。
    • variableDeclaration.getLeadingAnnotations().stream().anyMatch(...):遍历方法参数的所有前置注解,检查是否存在@NotNull。
    • addAttributeVisitor.visit(a, ctx, getCursor()):如果所有条件都满足,我们不直接修改a,而是将当前注解a、执行上下文ctx和当前游标getCursor()传递给addAttributeVisitor进行处理。这确保了AddOrUpdateAnnotationAttribute配方在正确的AST上下文下执行,避免了UncaughtVisitorException。

4. 编写测试用例

使用OpenRewrite的测试框架可以方便地验证配方的行为。

import org.junit.jupiter.api.Test;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class MandatoryRequestParameterTest implements RewriteTest {

    @Override
    public void defaults(RecipeSpec spec) {
        spec.recipe(new MandatoryRequestParameter())
            .parser(JavaParser.fromJavaVersion().classpath("spring-web", "validation-api")); // 确保classpath包含相关依赖
    }

    @Test
    void requiredRequestParamWithNotNull() {
        rewriteRun(
            java(
                """
                  import org.springframework.web.bind.annotation.RequestParam;
                  import javax.validation.constraints.NotNull;

                  class ControllerClass {
                      public String sayHello (
                          @NotNull @RequestParam(value = "name") String name, // 应该被修改
                          @RequestParam(value = "lang") String lang, // 不应被修改
                          @NotNull String address, // 不应被修改,因为它不是RequestParam
                          @NotNull @RequestParam(value = "age") Long age // 应该被修改
                      ) {
                         return "Hello";
                      }
                  }
                """,
                """
                  import org.springframework.web.bind.annotation.RequestParam;
                  import javax.validation.constraints.NotNull;

                  class ControllerClass {
                      public String sayHello (
                          @NotNull @RequestParam(required = true, value = "name") String name,
                          @RequestParam(value = "lang") String lang,
                          @NotNull String address,
                          @NotNull @RequestParam(required = true, value = "age") Long age
                      ) {
                         return "Hello";
                      }
                  }
                """
            )
        );
    }
}
登录后复制

测试用例说明:

  • defaults(RecipeSpec spec):配置测试环境,指定要运行的配方和Java解析器。classpath("spring-web", "validation-api")非常重要,它确保解析器能够识别@RequestParam和@NotNull注解的类型信息。
  • requiredRequestParamWithNotNull():定义一个测试方法。
    • java(...):接受两个字符串参数,第一个是修改前的源代码,第二个是期望修改后的源代码。OpenRewrite会运行配方并比较实际结果与期望结果。
    • 测试代码中包含了多种情况:
      • 同时有@NotNull和@RequestParam的参数(name, age):期望被修改。
      • 只有@RequestParam的参数(lang):不应被修改。
      • 只有@NotNull的参数(address):不应被修改。

总结

通过本文的介绍,我们了解了如何使用OpenRewrite的命令式配方,结合AST游标(Cursor)机制,实现对Java代码中特定注解组合的方法参数进行精确修改。关键在于:

  1. 选择正确的Visitor方法:根据要修改的AST节点类型(例如,修改注解则重写visitAnnotation)。
  2. 利用Cursor获取上下文:通过getCursor().getParent().getValue()等方法向上导航AST,获取当前节点所在的更高级别上下文(如方法参数声明)。
  3. 条件判断:在获取到上下文后,进行复杂的条件判断(例如,检查是否存在其他注解)。
  4. 委托子配方Visitor:当条件满足时,将修改操作委托给目标子配方的Visitor,并确保传递正确的当前AST节点、执行上下文和Cursor,以避免上下文错误。

这种细粒度的控制能力使得OpenRewrite成为处理复杂代码重构任务的强大工具。

以上就是如何使用OpenRewrite精准修改带有特定注解的方法参数的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号