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

如何创建可参数化的OpenRewrite Style并配置默认参数值

实现带参数的共享OpenRewrite导入样式方案

核心思路概述

通过OpenRewrite的样式参数化结合构建工具的内置属性传递,实现无需额外插件即可让样式自动读取项目group作为默认值,同时支持用户自定义变量值。

具体实现步骤

1. 定义参数化的共享Style

修改你的Style配置,将${projectRootPackage}声明为可配置参数,通过OpenRewrite的parameters字段暴露变量:

type: specs.openrewrite.org/v1beta/style
name: org.example.ParameterizedStyle
parameters:
  - name: projectRootPackage
    description: "项目根包路径,默认使用构建工具的group值"
    type: string
styleConfigs:
  - org.openrewrite.java.style.ImportLayoutStyle:
      classCountToUseStarImport: 999
      nameCountToUseStarImport: 999
      layout:
        - import java.*
        - <blank line>
        - import javax.*
        - <blank line>
        - import all other imports
        - <blank line>
        - import ${projectRootPackage}.*
        - <blank line>
        - import static all other imports

2. Maven项目中自动绑定默认值

在Maven的pom.xml里,直接通过OpenRewrite插件的configuration传递项目内置的${project.groupId}作为参数默认值,无需额外插件:

<build>
  <plugins>
    <plugin>
      <groupId>org.openrewrite.maven</groupId>
      <artifactId>rewrite-maven-plugin</artifactId>
      <version>5.40.0</version>
      <configuration>
        <activeRecipes>
          <recipe>org.example.ParameterizedStyle</recipe>
        </activeRecipes>
        <parameters>
          <projectRootPackage>${project.groupId}</projectRootPackage>
        </parameters>
      </configuration>
    </plugin>
  </plugins>
</build>

如果用户需要自定义值,只需修改<projectRootPackage>里的内容即可。

3. Gradle项目中自动绑定默认值

在Gradle的构建脚本中,利用Gradle的内置project.group属性传递参数,同样无需额外插件:

Groovy DSL

plugins {
  id 'java'
  id 'org.openrewrite.rewrite' version '6.12.0'
}

rewrite {
  activeRecipe("org.example.ParameterizedStyle")
  parameters = [
    projectRootPackage: project.group
  ]
}

Kotlin DSL

plugins {
  java
  id("org.openrewrite.rewrite") version "6.12.0"
}

rewrite {
  activeRecipe("org.example.ParameterizedStyle")
  parameters(mapOf(
    "projectRootPackage" to project.group
  ))
}

用户自定义时,直接替换project.group为指定包名即可。

4. 确保Style的可访问性

将这个参数化的Style打包发布到Maven仓库(或本地仓库),让用户可以通过构建工具的依赖引入,比如Maven中添加:

<dependencies>
  <dependency>
    <groupId>org.example</groupId>
    <artifactId>your-style-artifact</artifactId>
    <version>1.0.0</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

Gradle中添加:

dependencies {
  runtimeOnly("org.example:your-style-artifact:1.0.0")
}

关键原理说明

  • OpenRewrite的Style支持通过parameters字段定义可配置变量,在layout中通过${变量名}引用;
  • Maven和Gradle都内置了项目group的属性(project.groupId/project.group),可以直接传递给OpenRewrite插件的参数;
  • 这种方式完全基于OpenRewrite构建插件的原生DSL,无需编写额外插件或扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:22:45