You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenRewrite自定义SayHelloRecipe未接收配置值求助

解决OpenRewrite自定义Recipe参数无法接收配置值的问题

以下是排查和解决该问题的具体步骤:

1. 检查自定义Recipe的参数定义

确保你的SayHelloRecipe类正确使用@Option注解标记参数,并且提供对应的getter方法(OpenRewrite通过getter读取参数值,而非直接访问字段):

import org.openrewrite.Option;
import org.openrewrite.Recipe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SayHelloRecipe extends Recipe {
    private static final Logger logger = LoggerFactory.getLogger(SayHelloRecipe.class);

    @Option(
        displayName = "Fully Qualified Class Name",
        description = "目标类的全限定名称",
        required = true
    )
    private String fullyQualifiedClassName;

    // 必须提供getter方法,OpenRewrite通过反射读取参数
    public String getFullyQualifiedClassName() {
        return fullyQualifiedClassName;
    }

    // 必须包含公开的无参构造函数,用于OpenRewrite实例化
    public SayHelloRecipe() {}

    // 可选:用于单元测试的带参构造函数
    public SayHelloRecipe(String fullyQualifiedClassName) {
        this.fullyQualifiedClassName = fullyQualifiedClassName;
    }

    @Override
    public String getDisplayName() {
        return "Say Hello to specified class";
    }

    // 可选:添加日志验证参数是否加载
    @Override
    public void run(ExecutionContext ctx) {
        logger.info("Loaded fullyQualifiedClassName: {}", fullyQualifiedClassName);
        // 执行Recipe核心逻辑...
    }
}

注意:如果@Option指定了name属性,yml中的参数名必须和该值完全一致;未指定name时,默认使用字段的驼峰名称(如fullyQualifiedClassName)。

2. 验证rewrite.yml的配置格式

确保yml文件中正确配置Recipe的全限定类名和参数,参数需嵌套在对应Recipe节点下(YAML对缩进敏感,必须用空格缩进):

type: specs.openrewrite.org/v1beta/recipe
name: com.example.CustomRecipeCollection
displayName: 自定义Recipe集合
description: 包含SayHelloRecipe的自定义Recipe集合
recipes:
  - com.example.SayHelloRecipe:
      fullyQualifiedClassName: "com.example.target.DemoClass"

检查点:

  • Recipe的全限定类名必须和自定义类的包路径+类名完全一致
  • 参数名的拼写、大小写要和Recipe中@Option标记的名称完全匹配

3. 检查Maven插件的依赖配置

确保Maven的OpenRewrite插件依赖中包含了你的自定义Recipe所在的jar包,否则插件无法加载Recipe类,导致参数绑定失败:

<build>
  <plugins>
    <plugin>
      <groupId>org.openrewrite.maven</groupId>
      <artifactId>rewrite-maven-plugin</artifactId>
      <version>5.40.0</version>
      <configuration>
        <activeRecipes>
          <activeRecipe>com.example.SayHelloRecipe</activeRecipe>
        </activeRecipes>
      </configuration>
      <dependencies>
        <!-- 引入自定义Recipe的依赖 -->
        <dependency>
          <groupId>com.example</groupId>
          <artifactId>my-rewrite-recipes</artifactId>
          <version>1.0.0-SNAPSHOT</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

注意:如果自定义Recipe是当前项目的一部分,需确保它被正确打包到项目依赖中;如果是单独模块,需先安装到本地仓库或通过maven坐标引入。

4. 排查常见格式错误

  • 检查yml文件是否使用制表符缩进(YAML仅支持空格缩进)
  • 确保参数值的引号格式正确(包含特殊字符时必须用双引号包裹)
  • 核对Recipe类的包路径,避免因包名拼写错误导致插件找不到类

内容的提问来源于stack exchange,提问作者JustAnotherDeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 14:43:29