Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3526

Maven Spotless Plugin for Java

$
0
0

1. Overview

In this tutorial, we’ll explore the Maven Spotless Plugin, and use it to enforce a consistent code style across the project. Initially, we’ll use a minimal configuration to analyze the sourcode and address potential formatting violations. After that, we’ll gradually update the plugin’s configuration to use customized rules and execute these checks during a specific maven phase.

2. Getting Started

The Maven Spotless Plugin is a tool that automatically formats and enforces code style standards across various programming languages, during the build process. Getting started with Spotless is very easy, all we need to do is specify our preferred coding format in the spotless-maven-plugin.

Let’s start by adding the plugin to our pom.xml and configuring it to use the Google Java Style:

<plugin>
    <groupId>com.diffplug.spotless</groupId>
    <artifactId>spotless-maven-plugin</artifactId>
    <version>2.43.0</version>
    <configuration>
        <java>
            <googleJavaFormat/>
        </java>
    </configuration>
</plugin>

That’s it! We can now run “mvn spotless:check” and the plugin will automatically scan our Java files, and check if we use the correct formatting. In the console, we’ll see a summary of the files that were scanned, and how many of them have failures:

As we can see, if the plugin finds at least one formatting violation, the build will fail. If we scroll down, we’ll see a representation of the detected formatting issues. In this case, our code uses tabs, whereas the Google specification requires indentation blocks of two spaces:

Furthermore, Spotless will automatically fix all the violations, when we execute the command “mvn spotless::apply”. Let’s use the command to correct the violations, and compare the source code with the remote branch:

As we can notice, our source code was formatted correctly and it now complies with the Google Java standard.

3. Custom Formatting Rules

So far, we verified that our codebase uses consistent formatting, using a minimal configuration of the Spotless plugin. However, we can configure our own formatting rules using an Eclipse Formatter Profile. This profile is an XML file with a standardized structure that is compatible with a wide range of IDEs and formatting plugins.

Let’s add one of these files to the root folder of our project, we’ll call it baeldung-style.xml:

<profiles version="21">
    <profile kind="CodeFormatterProfile" name="baeldung-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"/>
        <!--   other settings...   -->
        <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>

Now, let’s update the pom.xml and add our custom formatter profile. We’ll remove the <googleJavaFormat/> step and replace it with a <eclipse> formatter that uses the settings from our custom XML file:

<plugin>
    <groupId>com.diffplug.spotless</groupId>
    <artifactId>spotless-maven-plugin</artifactId>
    <version>2.43.0</version>
    <configuration>
        <java>
            <eclipse>
                <file>${project.basedir}/baeldung-style.xml</file>
            </eclipse>
        </java>
    </configuration>
</plugin>

That’s it! Now we can re-run “mvn spotless:check” to ensure the project follows our custom conventions.

4. Additional Steps

Apart from verifying if the code is formatted properly, we can also use Spotless to perform static analysis and apply small improvements. After we specify the preferred code style in the plugin configuration, we can follow up with additional steps:

<java>
    <eclipse>
        <file>${project.basedir}/baeldung-style.xml</file>
    </eclipse>
    <licenseHeader>
        <content>/* (C)$YEAR */</content>
    </licenseHeader>
    <importOrder/>
    <removeUnusedImports />
    <formatAnnotations />
</java>

When we execute spotless:apply, each “step” will verify and enforce a specific rule:

  • <licenseHeader> checks if the files contain the correct copyright header,
  • <importOrder> and <removeUnusedImports> make sure the imports are relevant and follow a consistent order,
  • <formatAnnotations> ensures that type annotations are positioned on the same line as the fields they describe;

If we run the command, we can expect all these changes to be automatically applied:

5. Binding to a Maven Phase

Until now, we only used the Spotless plugin by directly triggering the maven goals “spotless:check” and “spotless:apply“. However, we can also bind these goals to a specific Maven phase. Phases are predefined stages in the Maven build lifecycle that execute tasks in a particular order to automate the software build process.

For example, the “package” phase bundles the compiled code and other resources into a distributable format, such as “Jar” or “War” files. Let’s use this phase to integrate with the Spotless plugin and execute “spotless:check“:

<plugin>
    <groupId>com.diffplug.spotless</groupId>
    <artifactId>spotless-maven-plugin</artifactId>
    <version>2.43.0</version>
    
    <configuration>
        <java>
            <!--  formatter and additional steps  -->
        </java>
    </configuration>
    
    <executions>
        <execution>
            <goals>
                <goal>check</goal>
            </goals>
            <phase>package</phase>
        </execution>
    </executions>
</plugin>

Consequently, Spotless’ check goal will be automatically executed during Maven’s package phase. In other words, we can enforce a consistent code style by causing the Maven build to fail if the source code does not adhere to the specified format and style guidelines.

6. Conclusion

In this article, we learned about the Maven Spotless Plugin, initially using it to enforce Google’s Java Format for static code analysis on our project. Then, we transitioned to a custom Eclipse Formatter Profile with our custom formatting rules.

Apart from formatting, we explored other configurable steps that can improve our code, and perform minor refactorings. Lastly, we discussed binding Spotless goals to specific Maven phases to ensure a consistent code style is enforced throughout the build process.

As always, the code examples can be found over on GitHub.

       

Viewing all articles
Browse latest Browse all 3526

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>