基于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

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

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



相关推荐
Sam_Deep_Thinking14 小时前
用Java 17从0到1写一个mini版RPC,理解远程调用的本质
java·面试·rpc·程序员·系统架构
敲代码的嘎仔14 小时前
从零搭建微服务:Spring Cloud Alibaba 全家桶踩坑实录(Nacos + OpenFeign + Gateway + Sentinel)
java·spring boot·spring·spring cloud·微服务·gateway·sentinel
一条泥憨鱼15 小时前
苍穹外卖【day7| 对购物车进行操作】
java·后端·mysql·苍穹外卖
都叫我大帅哥1 天前
Java JJWT 完全指南:从入门到生产级实践
java
前端开发张小七1 天前
Java 学习笔记 · 第一课:基础语法与核心概念
java·后端
ThsPool1 天前
【ENVI二次开发学习整理 04】ENVI功能扩展与二次开发
java·前端·javascript
赤壁小虾1 天前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
青山木1 天前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Jul1en_1 天前
【Claude Code Compact】源码级别的学习上下文压缩
java·前端·学习·github·ai编程
摇滚侠1 天前
《SpringBoot 3:入门与应用实战》第 15 章 生产级特性 管理 Spring Boot 应用 阅读笔记
java·spring boot·笔记