'How can I supress the checkstyle message "Utility classes should not have a public of default constructor" when using Spring

In a Spring Java project I have the following class:

@SuppressWarnings({"PMD", "Checkstyle"})
@SpringBootApplication
public class ToolBoxApplication {

    public static void main(final String[] args) {
        SpringApplication.run(ToolBoxApplication.class, args);
    }
}

Building using Jenkins tells me that I should not have a public or default constructor in a utility class.

In my checkstyle.xml withing Treewalker file I have

<!-- Make the @SuppressWarnings annotations available to Checkstyle -->
<module name="SuppressWarningsHolder" />

And the module

I tried to supress the specific check using

@SuppressWarnings({"PMD", "checkstyle:HideUtilityClassConstructor"})

but this did not work either. The "PMD" supression does work (it effectively reports the same error).



Solution 1:[1]

We have multiple spring boot applications, so instead of adding multiple @SuppressWarnings annotations, we configured a checkstyle suppression filter and added the following supression:

<!-- Spring Boot Application files get detected as utility classes and checkstyle wants them to have a private constructor, but a constructor is required to run the application. By convention application classes end with *Application -->
<suppress checks="HideUtilityClassConstructor" files=".*Application.java"/>

Solution 2:[2]

you can add a dummy method to avoid that rule too:

public void foo() {
    throw new UnsupportedOperationException();
}

Solution 3:[3]

This can be handled gracefully for the specific class. As this class is needed by the SpringBoot to launch the application so it won't have any other methods which makes it looks like a Utility Class.

Add below line in the suppressions.xml in your config/checkstyle folder. As you are excluding it only for specific file, its a good solution

 <suppress files="ToolBoxApplication.java"  checks="HideUtilityClassConstructor" />

If you dont have the suppressions.xml file then rather create one. It looks like below. (Ideally shouldn't have many suppressions)

<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
        "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
        "https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
    <suppress files="." checks="JavadocMethod"/>
    <suppress files="." checks="JavadocPackage"/>
    <suppress files="." checks="JavadocVariable"/>
    <suppress files="." checks="MissingJavadocMethod"/>
    <suppress files="." checks="JavadocPackage"/>
    <suppress files="ConversionProxyApplication.java"  checks="HideUtilityClassConstructor" />
</suppressions>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clarkey
Solution 2 devwebcl
Solution 3 Sanjay Bharwani