Comment on page

Running Rewrite on a Gradle project without modifying the build

In this tutorial, we will apply a Rewrite recipe to a source code repository built with Gradle without modifying the build itself. We will use a Gradle init script to accomplish this.

Step 1: Clone a repository

To have a reproducible example, we'll start with a repository generated from Spring Initializr. Select the "Gradle Project" option, click Generate, and extract the resultant zip file.

Step 2: Create a Gradle init script.

Save the following init script. It does not need to be in the project directory itself. In the rootProject block, we are specifying a dependency that contains OpenRewrite recipes (rewrite-java), and are also configuring a custom recipe YAML for use. For the full range of options, see Gradle Plugin Configuration.
initscript {
repositories {
maven { url "" }
dependencies {
rootProject {
dependencies {
rewrite {
afterEvaluate {
if (repositories.isEmpty()) {
repositories {

Step 3: Create the custom recipe YAML

The init script as configured above depends on a rewrite.yml that exists in the root of the project directory.
Here is what that might look like:
name: org.openrewrite.FindSpringUses
displayName: Find all Spring uses
description: This is an example of a custom recipe.
methodPattern: org.springframework..* *(..)

Step 4: Run the recipe

At this point, you are able to run the Rewrite gradle plugin as normal (with an additional --init-gradle argument). Note that we did not modify the project's build script. This same init script can then be used to apply this same recipe to a set of projects cloned locally without changing their contents.
gradle --init-script init.gradle rewriteRun