Skip to content
javahacks.dev
DevOps

How to Use OpenRewrite to Automate Java Code Upgrades

Use OpenRewrite recipes with Maven to upgrade Java, Spring Boot and test libraries automatically, review the patch and chain recipes of your own.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the Docker and Spring Boot logos.

Upgrading a Java codebase is mostly repetition. A new Spring Boot release renames a property in forty files, a Java release deprecates a constructor used in two hundred places, JUnit 4 imports have to become JUnit 5 imports in every test. People do this with find and replace and a lot of patience, and they miss a few. OpenRewrite does it with recipes: transformations that parse your code properly, change what they should and leave the rest alone. This post runs recipes through Maven, shows what the output looks like, composes a migration of your own and explains where automation stops and judgement starts. For the Spring side of an upgrade, Spring Boot from first project to production gives the context, and the Spring Boot guide covers the framework layer. The Java side of the build is in Maven's Java 25 compiler setup.

How OpenRewrite works

OpenRewrite parses Java, Kotlin, XML, YAML, properties, Gradle and Maven files into a lossless semantic tree. Lossless means whitespace and comments are kept in the model, so a transformation changes only the parts it means to and your diff stays small. Semantic means the tree knows types: a recipe that replaces String.valueOf(x) with something else can tell a String from a class that merely shares a method name, and an import change updates only references that really resolve to the old class.

A recipe is a named unit of change, published in a Maven artifact. Some are tiny (org.openrewrite.java.RemoveUnusedImports); some are composites that run dozens of others (org.openrewrite.java.migrate.UpgradeToJava21). You name the recipes you want; the plugin downloads them and runs them over your source.

Add the plugin and run a recipe

Put the plugin in the POM with the recipe module that holds your chosen recipe as a plugin dependency:

pom.xmlXML
<plugin>
    <groupId>org.openrewrite.maven</groupId>
    <artifactId>rewrite-maven-plugin</artifactId>
    <version>6.4.0</version>
    <configuration>
        <exportDatatables>true</exportDatatables>
        <activeRecipes>
            <recipe>org.openrewrite.java.migrate.UpgradeToJava21</recipe>
            <recipe>org.openrewrite.java.testing.junit5.JUnit4to5Migration</recipe>
        </activeRecipes>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.openrewrite.recipe</groupId>
            <artifactId>rewrite-migrate-java</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.openrewrite.recipe</groupId>
            <artifactId>rewrite-testing-frameworks</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>
</plugin>

Then the workflow is two commands. dryRun computes the changes and writes them out without touching your sources; run applies them.

Shell
./mvnw rewrite:dryRun
git apply --check target/rewrite/rewrite.patch
./mvnw rewrite:run

The dry run prints which recipes would change which files and leaves a unified diff in target/rewrite/rewrite.patch. Read it. A typical hunk from the Java 21 migration looks like this:

Diff
-        return Collections.unmodifiableList(new ArrayList<>(items));
+        return List.copyOf(items);
Diff
-        String name = (String) value;
-        if (value instanceof String) {
+        if (value instanceof String name) {

These are exactly the changes a careful person would make, applied everywhere at once. Run the whole test suite afterwards, commit the result as one change with the recipe names in the message, and keep it separate from feature work so the diff stays reviewable.

Chain recipes in rewrite.yml

Naming recipes in the POM works for one off runs. For a migration your team will repeat, or for mixing published recipes with your own rules, declare a composite recipe in a rewrite.yml at the project root:

rewrite.ymlYAML
---
type: specs.openrewrite.org/v1beta/recipe
name: dev.javahacks.PlatformUpgrade
displayName: Platform upgrade for the orders service
description: Java version, test library and logging changes agreed by the platform team.
recipeList:
  - org.openrewrite.java.migrate.UpgradeToJava21
  - org.openrewrite.java.testing.junit5.JUnit4to5Migration
  - org.openrewrite.java.testing.mockito.Mockito1to5Migration
  - org.openrewrite.java.ChangeType:
      oldFullyQualifiedTypeName: dev.javahacks.legacy.Money
      newFullyQualifiedTypeName: dev.javahacks.money.Money
  - org.openrewrite.java.ChangeMethodName:
      methodPattern: dev.javahacks.legacy.PaymentGateway charge(..)
      newMethodName: authorize

The last two entries are the payoff for a team with its own internal libraries. ChangeType moves every reference to a renamed class and fixes the imports. ChangeMethodName takes a method pattern, Type method(argument types) with .. matching any arguments, and renames every call site. These two cover a large share of what "we changed our shared library" costs its consumers. Activate the composite by setting <recipe>dev.javahacks.PlatformUpgrade</recipe> in activeRecipes.

Spring Boot and framework upgrades

Spring publishes recipes through the OpenRewrite project for each Boot line. Moving a service forward is one command, without editing the POM first:

Shell
./mvnw -U org.openrewrite.maven:rewrite-maven-plugin:run \
  -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:RELEASE \
  -Drewrite.activeRecipes=org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_5

The recipe bumps the parent version, renames deprecated properties in application.properties and application.yaml, changes removed annotations and fixes imports. Recipes for the next major line follow the same naming pattern. Check the recipe catalogue on docs.openrewrite.org for the exact name that matches your target, since the names are tied to a release.

What recipes do not do

Automation handles the mechanical part, which is most of the line count and little of the risk. The riskier part is behaviour: a changed default, a removed feature, a library that behaves differently on the new JDK. No recipe knows that your service depends on the old default for session cookie names. Expect to spend the saved time on the remaining failures:

  • Compile errors from APIs a recipe does not cover. Read the migration guide for each framework and search the build output.
  • Test failures caused by changed behaviour, not changed syntax.
  • Third party libraries that need a version bump the recipe did not make; check the dependency tree.

A reliable rhythm is: run the recipes, compile, fix what breaks, run the tests, fix what fails, and only then review. Commit the generated change before your manual fixes so a reviewer can see which lines a machine wrote and which a person did.

Failure modes

A dirty tree. Running a recipe on top of uncommitted work mixes the two. Start from a clean branch every time.

Recipe and dependency version drift. The recipe artifact versions, such as rewrite-migrate-java, must be compatible with the plugin version; a mismatch shows as a NoSuchMethodError inside the plugin. Update them together.

Unresolved types. Recipes that rely on type information need the project's compile classpath. If the build does not compile before you start, OpenRewrite parses with missing types and some recipes quietly skip those files. Make the build pass first.

Over broad composites. Running a hundred recipes at once yields a diff nobody reviews. Apply them in groups by concern, one commit each.

Writing your own small recipe

When a change is specific to your code and cannot be expressed with ChangeType and friends, the declarative route covers more than expected, and a Java recipe covers the rest. A Java recipe extends Recipe and returns a visitor. This one flags System.out.println so it can be replaced with a logger:

src/main/java/dev/javahacks/rewrite/FindPrintln.javajava
package dev.javahacks.rewrite;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.FindMethods;
import org.openrewrite.java.tree.J;

public class FindPrintln extends Recipe {
    @Override
    public String getDisplayName() {
        return "Find System.out.println calls";
    }

    @Override
    public String getDescription() {
        return "Marks calls to System.out.println so they can be replaced by a logger.";
    }

    @Override
    public TreeVisitor<?, ExecutionContext> getVisitor() {
        return new FindMethods("java.io.PrintStream println(..)", false).getVisitor();
    }
}

For most teams the declarative composites are enough. Reach for a Java recipe only when a pattern needs real logic, and test it with the rewrite-test library, which lets you write the before and after source as text blocks and asserts the transformation.

When this does not apply

A small project with a handful of deprecations is quicker to fix by hand. A codebase without tests gets less from automation, because you cannot tell whether the mechanical change preserved behaviour. And upgrades that are dominated by design changes, such as moving from servlet to reactive, are beyond recipes entirely. For the primary reference, the OpenRewrite documentation lists every recipe with its options, and the build side of your upgrade is covered in configuring the Maven compiler plugin for Java 25.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.