Maven Spotless Plugin for Java
Maintaining a consistent code style across a project is crucial for readability, collaboration, and long-term maintainability. The Maven Spotless Plugin is an excellent tool for enforcing code style and formatting rules in Java projects. This article provides a guide to configuring the Maven Spotless Plugin to maintain a consistent code style throughout a project.
1. Introduction to Maven Spotless Plugin
The Spotless Plugin is a general-purpose formatting tool that supports various languages, including Java. It can automatically apply formatting rules to your source code, helping maintain consistency across your project. In addition to Java, Spotless supports formatting for other file types like XML, JSON, Markdown, and more.
2. Initial Setup with Minimal Configuration
To start using the Spotless Plugin in a Maven project, we need to add the plugin configuration to our pom.xml
file.
Add the Spotless Plugin to pom.xml
<project> <!-- Other configurations --> <build> <plugins> <plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.43.0</version> <configuration> <java> <googleJavaFormat/> </java> </configuration> </plugin> </plugins> </build> </project>
In this configuration, Spotless uses Google’s Java Format by default, ensuring that the code adheres to a widely accepted style guide.
Analyze the Source Code
To analyze your source code and check for formatting violations, run the following Maven command:
mvn spotless:check
This command checks the code against the configured formatting rules. If any violations are found, Spotless will report them. When we run the above mvn
command (spotless:check
), Maven checks your project’s source code against the formatting rules specified in the plugin’s configuration and if it encounters formatting violations, it does the following:
- Identifies Violations: Maven compares your code against the formatting rules defined in the Spotless Plugin configuration. If any part of the code does not conform to these rules, it is flagged as a violation.
- Outputs Detailed Reports: Maven will print detailed information about each formatting violation in the console. This output includes the file name, line number, and a brief description of the issue, showing you exactly where the code deviates from the expected format. Example output is:
- Fails the Build: If any formatting violations are found, Maven will fail the build process. This behaviour is intentional to ensure that improperly formatted code does not get merged or deployed.
Automatically Fixing All Violations
To automatically fix all formatting violations, we can use the spotless:apply
goal. This goal will reformat your code according to the rules specified in the Spotless configuration. Execute the following Maven command to apply the formatting rules and fix all violations:
mvn spotless:apply
After running spotless:apply
, Maven will provide output confirming that the formatting has been applied successfully.
2.1 What Happens During spotless:apply
:
- Applies Formatting Rules: Spotless will automatically reformat all the code that doesn’t adhere to the configured style guidelines. This includes adjusting indentation, spacing, line breaks, and other formatting aspects to match the specified rules.
- Updates Source Files: The source files with violations will be modified directly, correcting the formatting issues. The updated files will now conform to the formatting rules defined in your Spotless configuration.
- Confirms Success: After running
spotless:apply
, Maven will provide output confirming that the formatting has been applied successfully.
To confirm that all violations have been resolved, we can re-run the spotless:check
goal. If no further violations are detected, the build will succeed, verifying that our codebase now complies with the defined formatting standards.
3. Customizing Code Formatting and Analysis
To enforce custom formatting rules with the Maven Spotless Plugin, we can create a style.xml
file that defines our preferred code style settings. Here is how we can create this file and configure Spotless to use it.
Create a file named style.xml
in your project’s root directory (or any preferred location), and include the following content:
<?xml version="1.0" encoding="utf-8"?> <profiles version="21"> <profile kind="CodeFormatterProfile" name="style" version="21"> <setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/> <setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="true"/> <setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/> <setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/> <setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/> <setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/> <setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/> <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/> </profile> </profiles>
In your pom.xml
, configure the Spotless Plugin to use the custom style.xml
file for formatting.
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.43.0</version> <configuration> <java> <eclipse> <file>${project.basedir}/style.xml</file> </eclipse> </java> </configuration> </plugin>
Replace
with the actual path to your $
{project.basedir}/style.xmlstyle.xml
file relative to the project root.
Spotless not only helps in formatting code but also can be used to perform static analysis and apply small improvements, such as organizing imports or removing unnecessary whitespace. We can configure Spotless to automatically organize imports according to a specified order.
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.43.0</version> <configuration> <java> <eclipse> <file>path/to/style.xml</file> </eclipse> <importOrder> <order>java,javax,org,com</order> </importOrder> </java> </configuration> </plugin>
To remove unnecessary whitespace (e.g., trailing spaces), Spotless can be configured as follows:
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.43.0</version> <configuration> <java> <eclipse> <file>path/to/style.xml</file> </eclipse> <removeTrailingWhitespace/> <endWithNewline/> </java> </configuration> </plugin>
After configuring Spotless with our custom style.xml
, we can run the following commands to perform static analysis and apply improvements. To check for violations, run mvn spotless:check
. To apply fixes, run mvn spotless:apply
4. Executing Spotless During a Specific Maven Phase
We can configure Spotless to run automatically during a specific Maven phase, such as validate
or verify
. This ensures that the formatting checks are part of our build process. The configuration below shows how to configure Spotless to run during the verify
phase.
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.43.0</version> <executions> <execution> <goals> <goal>check</goal> </goals> <phase>verify</phase> </execution> </executions> <configuration> <java> <googleJavaFormat/> </java> </configuration> </plugin>
In this configuration, Spotless will run the check
goal during the verify
phase. If any formatting violations are found, the build will fail.
5. Conclusion
In this article, we explored the Maven Spotless Plugin’s capabilities for enforcing a consistent code style in Java projects. We began with a basic configuration to identify and correct formatting violations, then gradually customized the plugin’s settings to meet specific project requirements. Additionally, we discussed how to integrate Spotless checks into the Maven build process and automatically resolve formatting issues.
6. Download the Source Code
This article covered the Java Maven Spotless Plugin.
You can download the full source code of this example here: java maven spotless plugin