
本文深入探讨了如何利用OpenRewrite框架,针对Java代码中具有特定注解组合(例如`@NotNull`和`@RequestParam`)的方法参数进行精细化改造。我们将介绍声明式和命令式两种配方(Recipe)的实现方式,重点演示如何通过命令式配方结合AST游标(Cursor)机制,实现对代码元素的上下文感知式修改,从而避免常见的`UncaughtVisitorException`,并提供详细的代码示例及测试方法。
OpenRewrite是一个强大的自动化代码重构工具,通过编写配方(Recipe)来识别和修改代码模式。在实际开发中,我们经常需要对代码进行有条件的、细粒度的修改,例如只修改同时带有@NotNull和@RequestParam注解的方法参数,为其@RequestParam注解添加required = true属性。本文将详细介绍如何实现这一目标。
在尝试对特定代码片段应用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。
对于简单的、无条件的代码修改,声明式配方是一种快速有效的方法。你可以通过一个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)的修改。
当需要根据复杂的条件来决定是否应用修改时,命令式配方是更合适的选择。它允许我们通过编写Java代码来遍历抽象语法树(AST),并利用Cursor来获取当前代码元素的上下文信息。
目标: 仅为同时带有@NotNull和@RequestParam注解的方法参数,将其@RequestParam注解的required属性设置为true。
核心思路:
实现步骤:
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;
}
};
}
}代码解释:
使用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";
}
}
"""
)
);
}
}测试用例说明:
通过本文的介绍,我们了解了如何使用OpenRewrite的命令式配方,结合AST游标(Cursor)机制,实现对Java代码中特定注解组合的方法参数进行精确修改。关键在于:
这种细粒度的控制能力使得OpenRewrite成为处理复杂代码重构任务的强大工具。
以上就是如何使用OpenRewrite精准修改带有特定注解的方法参数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号