
本文深入探讨了如何使用 openrewrite 框架,针对 java 代码中特定方法参数的注解进行精确修改。文章首先介绍了声明式配方的简洁性及其局限性,随后重点阐述了通过命令式配方结合 `javavisitor` 和 `cursor` 实现细粒度控制的方法。通过具体示例,详细讲解了如何根据参数的类型、名称或其他注解等条件,有选择性地更新或添加注解属性,并提供了测试配方的实践指导。
OpenRewrite 是一个强大的代码重构工具,它允许开发者通过编写“配方”(Recipe)来自动化修改代码库。这些配方可以用于升级依赖、修复安全漏洞、统一代码风格等。在实际开发中,我们经常需要对代码进行有条件的修改,例如,仅针对满足特定条件的方法参数应用或更新注解属性。本文将详细介绍如何实现这一目标。
假设我们需要为 Spring 框架中同时带有 @NotNull 和 @RequestParam 注解的方法参数,将 @RequestParam 的 required 属性设置为 true。例如,将以下代码:
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
) {
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
) {
return "Hello";
}
}注意,只有第一个参数 name 需要修改,因为它同时拥有 @NotNull 和 @RequestParam。第二个参数 lang 没有 @NotNull 注解,因此不应被修改。
初次尝试的命令式配方可能如下所示,但它在运行时会抛出 org.openrewrite.UncaughtVisitorException: java.lang.IllegalStateException: Expected to find a matching parent for Cursor{Annotation->root} 错误。这通常是因为 AddOrUpdateAnnotationAttribute 配方被应用到了一个不正确的 AST 上下文(例如,将其直接应用于 Statement 而非其内部的 Annotation 节点,或者 Cursor 没有提供正确的父级信息)。
public class MandatoryRequestParameter extends Recipe {
@Override
public @NotNull String getDisplayName() {
return "Make RequestParam mandatory";
}
@Override
protected @NotNull JavaIsoVisitor<ExecutionContext> getVisitor() {
return new MandatoryRequestParameterVisitor();
}
public class MandatoryRequestParameterVisitor extends JavaIsoVisitor<ExecutionContext> {
@Override
public @NotNull J.MethodDeclaration visitMethodDeclaration(@NotNull J.MethodDeclaration methodDeclaration, @NotNull ExecutionContext executionContext) {
J.MethodDeclaration methodDecl = super.visitMethodDeclaration(methodDeclaration, executionContext);
// 错误的应用方式:直接在参数列表上映射并尝试修改
return methodDeclaration.withParameters(ListUtils.map(methodDecl.getParameters(), (i, p) -> makeRequestParamMandatory(p, executionContext)));
}
private Statement makeRequestParamMandatory(Statement statement, ExecutionContext executionContext) {
if (!(statement instanceof J.VariableDeclarations methodParameterDeclaration) || methodParameterDeclaration.getLeadingAnnotations().size() < 2) {
return statement;
}
AddOrUpdateAnnotationAttribute addOrUpdateAnnotationAttribute = new AddOrUpdateAnnotationAttribute(
"org.springframework.web.bind.annotation.RequestParam", "required", "true", false
);
// 错误:直接将 AddOrUpdateAnnotationAttribute 应用到 VariableDeclarations
return (Statement) methodParameterDeclaration.acceptJava(addOrUpdateAnnotationAttribute.getVisitor(), executionContext);
}
}
}这个错误提示说明 AddOrUpdateAnnotationAttribute 配方期望在其内部访问一个 J.Annotation 节点,并且该注解节点需要在一个正确的 AST 结构中,以便 Cursor 能够找到其父级。直接将 AddOrUpdateAnnotationAttribute 的访问器应用于 J.VariableDeclarations 节点是不正确的,因为它期望直接处理 J.Annotation。
OpenRewrite 提供了两种主要的配方编写方式:声明式(YAML)和命令式(Java)。
对于简单的、无条件的代码修改,声明式配方是一个快速有效的选择。例如,要全局地将所有 @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"应用方式:
将上述 YAML 文件放在项目根目录,并通过 Maven 或 Gradle 插件激活该配方。
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>
</plugin>局限性: 声明式配方适用于全局性、无条件的修改。然而,它无法实现我们最初的需求——根据其他注解、参数类型或名称等条件来限制修改范围。为了实现这种精细控制,我们需要使用命令式配方。
命令式配方允许我们编写 Java 代码来遍历抽象语法树(AST),并根据复杂的逻辑判断来修改代码。解决上述问题的关键在于正确使用 JavaVisitor 和 Cursor。
核心概念:JavaVisitor 和 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.Statement;
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.internal.ListUtils;
import javax.validation.constraints.NotNull;
import java.util.List;
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 "Add `required` attribute to `RequestParam` and set the value to `true` only for specific parameters.";
}
@Override
protected TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
// 优化:只有当源文件包含 RequestParam 注解时才运行访问器
return new UsesType<>(REQUEST_PARAM_FQ_NAME);
}
@Override
protected @NotNull JavaVisitor<ExecutionContext> getVisitor() {
// 创建 AddOrUpdateAnnotationAttribute 的访问器实例,用于实际的注解属性修改
JavaIsoVisitor<ExecutionContext> 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);
// 检查当前注解是否为 RequestParam
if (!TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME)) {
return a;
}
// 使用 Cursor 获取当前注解的父节点。
// 对于方法参数上的注解,其父节点通常是 J.VariableDeclarations。
J.VariableDeclarations variableDeclaration = getCursor().getParent().getValue();
// 实现条件逻辑:
// 1. 检查参数是否带有 @NotNull 注解
boolean hasNotNull = variableDeclaration.getLeadingAnnotations().stream()
.anyMatch(ann -> TypeUtils.isOfClassType(ann.getType(), NOT_NULL_FQ_NAME));
// 2. 示例条件:如果参数类型是 java.lang.Number 的子类型
boolean isNumberType = TypeUtils.isAssignableTo("java.lang.Number", variableDeclaration.getType());
// 3. 示例条件:如果参数名为 "fred"
boolean isNamedFred = variableDeclaration.getVariables().get(0).getSimpleName().equals("fred");
// 满足任一条件(或按实际需求组合条件),则应用修改
// 原始问题是要求同时有 @NotNull 和 @RequestParam,所以这里组合条件
if (hasNotNull /* && 其他条件 */) { // 满足原始问题条件
// 如果满足条件,将修改委托给 AddOrUpdateAnnotationAttribute 的访问器
// 注意:这里传入了当前的 Cursor,确保 AddOrUpdateAnnotationAttribute 在正确的上下文中执行
return (J.Annotation) addAttributeVisitor.visit(a, ctx, getCursor());
}
// 也可以根据其他条件进行修改,例如:
// if (isNumberType || isNamedFred) {
// return (J.Annotation) addAttributeVisitor.visit(a, ctx, getCursor());
// }
return a;
}
};
}
}代码解析:
OpenRewrite 提供了强大的测试工具来验证配方的行为。在 JUnit 测试中,你可以使用 rewriteRun 方法来定义输入代码和期望的输出代码。
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;
import static org.openrewrite.test.RewriteTest.rewriteRun;
class MandatoryRequestParameterTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new MandatoryRequestParameter())
.parser(JavaParser.fromJavaVersion().classpath("spring-web")); // 确保 classpath 包含 Spring Web 依赖
}
@Test
void requiredRequestParamWithNotNullAndOtherConditions() {
rewriteRun(
java(
"""
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.NotNull; // 导入 NotNull 注解
class ControllerClass {
public String sayHello (
@NotNull @RequestParam(value = "name") String name, // 期望被修改
@RequestParam(value = "lang") String lang, // 不期望被修改
@NotNull @RequestParam(value = "aNumber") Long aNumber, // 期望被修改 (同时有 NotNull)
@RequestParam(value = "fred") String fred, // 期望被修改 (如果配方中包含 name="fred" 的条件)
@NotNull String justNotNull // 不期望被修改 (没有 RequestParam)
) {
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 @RequestParam(required = true, value = "aNumber") Long aNumber,
@RequestParam(value = "fred") String fred, // 根据配方条件,此项可能不变或改变
@NotNull String justNotNull
) {
return "Hello";
}
}
"""
)
);
}
}在上述测试中,defaults 方法用于配置测试规范,包括要运行的配方和 Java 解析器。requiredRequestParamWithNotNullAndOtherConditions 测试方法则定义了输入代码和期望的输出代码,用于验证配方在不同场景下的行为。请注意,classpath("spring-web") 是为了确保解析器能够正确解析 Spring 相关的注解。
通过本文的讲解,我们了解了 OpenRewrite 声明式配方和命令式配方的不同应用场景。当需要对代码进行精细的、条件性的修改时,命令式配方结合 JavaVisitor 和 Cursor 是实现这一目标的关键。特别是 Cursor 允许我们获取 AST 节点的上下文信息,从而能够根据父节点(如 J.VariableDeclarations)的属性(如其他注解、类型、名称)来决定是否应用修改。掌握这一技术,将大大提升 OpenRewrite 在复杂代码重构任务中的灵活性和效率。在编写配方时,务必注意 AST 结构和 Cursor 的正确使用,并通过完善的测试来验证配方的行为。
以上就是OpenRewrite:针对特定方法参数应用和定制注解属性的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号