
本教程深入探讨如何使用openrewrite对java代码进行精细化改造,特别是针对spring框架中带有特定注解(如`@notnull`和`@requestparam`)的方法参数。文章将介绍两种策略:声明式yaml配方适用于全局修改,而命令式java配方则通过`javavisitor`和`cursor`机制实现高度定制化的条件判断和精确的代码元素定位,从而避免常见的上下文错误,确保只对满足特定条件的参数应用修改,提升代码重构的效率和准确性。
在软件开发和维护过程中,代码重构是一项常见任务。当需要对大量代码库进行统一的、模式化的修改时,手动操作不仅效率低下,还极易出错。OpenRewrite作为一款强大的自动化代码重构工具,能够通过定义“配方”(Recipe)来批量转换代码。然而,实际应用中往往需要对代码的特定部分进行修改,而非简单地全局替换。本文将详细介绍如何利用OpenRewrite实现对Java方法参数的精确定位与修改,以满足诸如为同时带有@NotNull和@RequestParam注解的参数添加required = true属性的需求。
OpenRewrite通过构建抽象语法树(AST)来理解和操作代码。一个“配方”本质上是一系列对AST节点的访问和转换操作。常见的挑战在于,如何将这些操作限制在满足特定条件的AST节点上,而不是无差别地应用到整个文件或所有匹配的节点。例如,我们希望仅修改那些既有@NotNull又有@RequestParam注解的方法参数,为其@RequestParam注解添加required = true属性。
原始尝试中,直接在J.VariableDeclarations(方法参数声明)中调用AddOrUpdateAnnotationAttribute的getVisitor()方法,并尝试将其应用于注解,导致了IllegalStateException: Expected to find a matching parent for Cursor{Annotation->root}。这表明AddOrUpdateAnnotationAttribute的访问器在被调用时,需要一个正确的Cursor上下文来理解其操作的父节点。直接在参数声明的循环中调用一个针对注解的访问器,并传入不正确的上下文,是导致此错误的关键原因。
对于相对简单的、不涉及复杂条件判断的全局修改,OpenRewrite提供了声明式配方,通过YAML文件进行配置。这种方式简洁明了,易于理解和部署。
以下是一个声明式配方,用于为所有@RequestParam注解添加required=true属性:
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文件保存为rewrite.yml在项目根目录,并通过OpenRewrite的Maven或Gradle插件激活。
Maven配置示例:
在pom.xml中添加或修改rewrite-maven-plugin配置:
<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>局限性:
声明式配方虽然方便,但其主要局限在于无法直接表达复杂的条件逻辑。例如,如果只想修改同时带有@NotNull注解的@RequestParam,声明式配方就难以实现。这时,就需要使用命令式Java配方。
当需要根据复杂的条件(如:是否存在其他特定注解、参数类型、参数名称等)来决定是否应用修改时,命令式Java配方提供了无与伦比的灵活性。
以下是一个命令式Java配方,它展示了如何有条件地修改@RequestParam注解。此示例以参数类型为java.lang.Number或参数名为"fred"作为条件,但其机制可以轻松扩展以检查@NotNull注解的存在。
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 org.openrewrite.internal.lang.Nullable;
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 "Add `required` attribute to `RequestParam` and set the value to `true` based on specific conditions.";
}
/**
* 优化:仅当源文件包含 `RequestParam` 注解时才运行此配方。
*/
@Override
protected @Nullable TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
return new UsesType<>(REQUEST_PARAM_FQ_NAME);
}
@Override
protected @NotNull JavaVisitor<ExecutionContext> getVisitor() {
// 创建一个用于添加或更新注解属性的内部访问器
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);
// 1. 检查当前注解是否是 @RequestParam
if (!TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME)) {
return a;
}
// 2. 使用 Cursor 向上导航,获取父级 J.VariableDeclarations (即方法参数声明)
// 解决原始问题中 IllegalStateException 的关键点:
// AddOrUpdateAnnotationAttribute 需要正确的父级上下文。
// 通过 getCursor().getParent().getValue() 确保我们是在正确地操作注解的父级。
J.VariableDeclarations variableDeclaration = getCursor().getParent().getValue();
// 3. 定义条件:
// 示例条件一:参数类型是 java.lang.Number 或其子类型
// 示例条件二:参数名称是 "fred"
// 扩展条件:检查参数是否也带有 @NotNull 注解
boolean shouldApply = false;
JavaType paramType = variableDeclaration.getType();
if (TypeUtils.isAssignableTo("java.lang.Number", paramType) ||
variableDeclaration.getVariables().get(0).getSimpleName().equals("fred")) {
shouldApply = true;
}
// 检查是否存在 @NotNull 注解 (根据原始问题需求扩展)
// 遍历参数声明上的所有注解,查找 @NotNull
boolean hasNotNullAnnotation = variableDeclaration.getLeadingAnnotations().stream()
.anyMatch(ann -> TypeUtils.isOfClassType(ann.getType(), NOT_NULL_FQ_NAME));
if (hasNotNullAnnotation && TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME)) {
// 如果同时有 @NotNull 和 @RequestParam,则应用修改
shouldApply = true;
}
// 4. 如果满足条件,则委托给内部的 addAttributeVisitor 进行修改
if (shouldApply) {
// 将当前注解 'a' 和其正确的 Cursor 上下文传递给内部访问器
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 requiredRequestParam() {
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)
@NotNull @RequestParam(value = "aNumber") Long aNumber, // 期望修改 (有 @NotNull 且类型为 Number)
@NotNull @RequestParam(value = "fred") String fred // 期望修改 (有 @NotNull 且名称为 "fred")
) {
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,
@NotNull @RequestParam(required = true, value = "fred") String fred
) {
return "Hello";
}
}
"""
)
);
}
}在上述测试中,defaults方法设置了配方和解析器。@Test方法则定义了输入源代码和期望的输出源代码,OpenRewrite会自动比较两者以验证配方的正确性。classpath("spring-web", "validation-api")确保了@RequestParam和@NotNull注解能够被正确解析。
本文详细介绍了如何利用OpenRewrite对Java方法参数进行精确定位和修改。对于简单的全局修改,声明式YAML配方提供了一种快速便捷的方式。然而,当需要复杂的条件判断时,命令式Java配方结合JavaVisitor和Cursor机制,能够实现高度定制化的代码转换。通过理解和正确使用Cursor进行AST导航,开发者可以避免常见的上下文错误,并构建出强大且精确的自动化代码重构工具。掌握这些技术,将极大地提升代码重构的效率和准确性。
以上就是OpenRewrite:精确定位与修改特定方法参数的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号