What is OpenRewrite?
OpenRewrite is a tool that can be used to perform large, automated refactorings. For various use cases, such as framework migrations, API migrations and much more, there are various Recipes. Simple recipes for Java, for example, offer the possibility, remove unused imports or add missing license header. But there are also more complex recipes that require a Migration to Java 17 or the upgrade from Spring Boot 2.x to Spring Boot 3.0 enable.
How does OpenRewrite work?
OpenRewrite does not use a simple "search and replace", but a semantic search. More precisely, it uses Lossless Semantic Trees. The individual elements of the Java classes are transferred into a tree structure. The actions are then carried out on the basis of these elements. There is more detailed information on how this works here. If you understand how OpenRewrite works, you can also implement your own recipes. Most of the larger recipes consist of many smaller recipes. Existing recipes can therefore also be reused.
How do I use it?
OpenRewrite can be used either via Maven or Gradle. The following steps must be carried out for Maven. The snippets for the plugin configuration or the corresponding one-liner command can be found on the documentation page and can simply be copied.
Add plugin with corresponding recipe
<build> <plugins> <plugin> <groupId>org.openrewrite.maven</groupId> <artifactId>rewrite-maven-plugin</artifactId> <version>5.3.2</version> <configuration> <activeRecipes> <recipe>org.openrewrite.java.migrate.UpgradeToJava17</recipe> </activeRecipes> </configuration> <dependencies> <dependency> <groupId>org.openrewrite.recipe</groupId> <artifactId>rewrite-migrate-java</artifactId> <version>2.1.0</version> </dependency> </dependencies> </plugin> </plugins></build> |
Execute Maven Command
mvn rewrite:run |
Alternative
If you do not want to customize your project, you can also execute the Maven command directly. For the example above, this looks as follows:
mvn -U org.openrewrite.maven:rewrite-maven-plugin:run \ -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-migrate-java:RELEASE \ -Drewrite.activeRecipes=org.openrewrite.java.migrate.UpgradeToJava17 |
After the recipe has been executed, it is still advisable to check all adjustments again.
Further information on the design can be found at: https://docs.openrewrite.org/running-recipes
Conclusion
At doubleSlash, OpenRewrite has now been used successfully in several projects. In some cases, microservices were updated from Spring 2.x to 3.0 in under an hour, including an update from Java 11 to Java 17. It is therefore definitely worth taking a look at the OpenRewrite recipes https://docs.openrewrite.org/recipes. There is probably something here for every project and there are now recipes for many other languages, frameworks and libraries in addition to Java.
Image source:



