使用OpenRewrite轻松升级项目到Spring Boot3

2,536 阅读2分钟

OpenRewrite 项目简介

OpenRewrite 是一款用于执行框架迁移、安全修复和代码风格一致性任务的自动化重构工具。它能够通过修改构建文件、更新弃用的 API 和迁移配置来简化代码升级过程。

核心特性

  1. 代码自动化重构:自动重构代码,无需手动更改。
  2. 可扩展性强:支持编写自定义规则,满足特定重构需求。
  3. 语义分析:基于抽象语法树 (AST) 进行代码深度分析和修改。

使用场景

  1. 库和框架迁移:如从 Spring Boot 2.x 升级到 3.x。
  2. 修复安全漏洞:自动替换过时或不安全的依赖。
  3. 代码风格统一:自动格式化代码,符合团队编码标准。
  4. 消除技术债务:检测并修复代码坏味道 (Code Smells)。

简单使用示例

以下以官方案例项目 spring-petclinic-migration 为例:

将 OpenRewrite 插件添加到 Maven 项目中:

<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>5.43.0</version>
</plugin>

然后添加activeRecipes配置到 OpenRewrite 插件,这里以org.openrewrite.java.format.AutoFormat配方为例

添加并启用 AutoFormat 配方:

<configuration>
    <activeRecipes>
        <recipe>org.openrewrite.java.format.AutoFormat</recipe>
    </activeRecipes>
</configuration>

运行命令:mvn rewrite:run,完成后可以看到成功对代码进行了格式化。

image.png


有些配方较为复杂,需要配置在rewrite.yml文件中运行。

org.openrewrite.java.ChangePackage配方为例:

创建 rewrite.yml

---
type: specs.openrewrite.org/v1beta/recipe
name: com.example.ChangePackage
recipeList:
  - org.openrewrite.java.ChangePackage:
      oldPackageName: org.example.old
      newPackageName: org.example.new

修改插件配置

<configuration>
    <activeRecipes>
        <recipe>com.example.ChangePackage</recipe>
    </activeRecipes>
</configuration>

再次使用 mvn rewrite:run 运行,包名成功改为org.springframework.samples.petclinic.veterinary


升级项目到 Spring Boot 3

可以自己来根据需求编写 配方(Recipe), 具体可参考官方文档 docs.openrewrite.org/authoring-r…

也可以直接使用官方提供的配方, docs.openrewrite.org/recipes 列出了官方提供的所有 OpenRewrite 配方。

这里使用UpgradeSpringBoot_3_3,根据文档内容配置 OpenRewrite 插件

<plugin>
  <groupId>org.openrewrite.maven</groupId>
  <artifactId>rewrite-maven-plugin</artifactId>
  <version>5.43.0</version>
  <configuration>
    <activeRecipes>
      <recipe>org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3</recipe>
    </activeRecipes>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.openrewrite.recipe</groupId>
      <artifactId>rewrite-spring</artifactId>
      <version>5.22.0</version>
    </dependency>
  </dependencies>
</plugin>

运行命令后,Spring Boot 成功升级至 3.3.5,Java 版本更新为 17。

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>3.3.5</version>
</parent>

<properties>
  <maven.compiler.source>${java.version}</maven.compiler.source>
  <maven.compiler.target>${java.version}</maven.compiler.target>

  <!-- Generic properties -->
  <java.version>17</java.version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

</properties>

使用 idea 插件

IntelliJ IDEA 提供了与 OpenRewrite 的集成:

安装并启用 OpenRewrite 插件。

image.png

在 Maven 或 Gradle 项目中,可直接查看和运行迁移配方。

image.png image.png

总结

OpenRewrite 是一个功能强大的自动化重构工具,能够帮助开发者轻松完成代码迁移。通过支持自定义配方解决具体问题,极大地提高了代码维护和升级的效率。