基于Maven 运行OpenRewrite的快速示例

本篇介绍一个基于Maven 运行OpenRewrite 的快速示例,展示了如何在Maven项目中使用OpenRewrite 进行代码重构。

本篇达成的效果是使用OpenRewrite 对源码自动格式化。

达成效果期望

项目中有一个类AutoFormatDemo ,类的代码如下

复制代码
public class AutoFormatDemo {public static void main(String[]args){System.out.println("Hello, World!");}}

使用OpenRewrite 自动格式化上面的代码。

步骤

  1. 在Maven项目中已经添加OpenRewrite Maven插件, 具体是在pom.xml 的<plugins> 节点添加插件

    org.openrewrite.maven rewrite-maven-plugin 5.34.1
  • 这里的version 可以配置使用最新的版本

命令行运行mvn rewrite:discover 可以查看所有可执行的配方列表, 执行的效果如下:

  1. 激活配方

在运行任何配方之前,需要更新插件配置以将所需配方标记为"active"。

OpenRewrite 官方提供了代码格式化的配方 org.openrewrite.java.format.AutoFormat。关于该配方的详细介绍可以参考:
OpenRewrite配方之代码格式化------org.openrewrite.java.format.AutoFormat

要激活这个配方,可以在pom.xml 中将插件的配置修改为:

复制代码
<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>5.34.1</version>
  <configuration>
    <activeRecipes>
      <recipe>org.openrewrite.java.format.AutoFormat</recipe>
    </activeRecipes>
  </configuration>
</plugin>
  1. 运行配方
    上面激活配方之后, 接下来就可以运行了。在命令行输入如下命令:

    mvn rewrite:run

执行过程中,控制台会输出如下信息:

查看原来的代码,会被格式化成如下:



相关推荐
wangchunyu1148 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
paopaokaka_luck8 小时前
流浪动物救助与收养系统(DeepSeek AI对话、 ECharts多维分析、救助流程衔接、领养与回访衔接、 捐赠确认与公示、志愿者协作)
java·前端·javascript·人工智能·mysql·echarts·推荐算法
Thomas.Sir8 小时前
第9课:SpringBoot4.x Web开发基础:WebMvc自动配置、静态资源、请求参数接收
java·spring boot
程序 代码狂人9 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
警醒与鞭策9 小时前
Codex桌面版与Claude桌面版使用设置
android·unity·ai·性能优化
2501_944521599 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
南归北隐11 小时前
Spring AI Alibaba Graph框架实现MCP数据库查询实战
java·后端·spring ai·mcp·spring ai mcp
古法老登瞎折腾11 小时前
大数据智能运维实战(九):让 AI 查日志——找到异常,也保留上下文
java·大数据·运维·人工智能·spring ai·mcp
ai大模型-探索者11 小时前
Function Call与MCP(区别、联系与实战)
java·服务器·网络
略略略咯咯11 小时前
啊啊啊啊啊
java·服务器·数据库