Giter Club home page Giter Club logo

spring-javaformat's Introduction

Spring Java Format

What is This?

A set of plugins that can be applied to any Java project to provide a consistent “Spring” style. The set currently consists of:

  • A source formatter that applies wrapping and whitespace conventions

  • A checkstyle plugin that enforces consistency across a codebase

Since the aim of this project is to provide consistency, each plugin is not generally configurable. You need to change your code to match the required conventions. You can’t configure the plugin conventions to match your style!

Maven

Source Formatting

For source formatting, add the spring-javaformat-maven-plugin to your build plugins as follows:

<build>
	<plugins>
		<plugin>
			<groupId>io.spring.javaformat</groupId>
			<artifactId>spring-javaformat-maven-plugin</artifactId>
			<version>0.0.42</version>
		</plugin>
	</plugins>
</build>

And the io.spring.javaformat plugin group in ~/.m2/settings.xml as follows:

<pluginGroups>
	<pluginGroup>io.spring.javaformat</pluginGroup>
</pluginGroups>

You can now run ./mvnw spring-javaformat:apply to reformat code.

If you want to enforce that all code matches the required style, add the following:

<build>
	<plugins>
		<plugin>
			<groupId>io.spring.javaformat</groupId>
			<artifactId>spring-javaformat-maven-plugin</artifactId>
			<version>0.0.42</version>
			<executions>
				<execution>
					<phase>validate</phase>
					<inherited>true</inherited>
					<goals>
						<goal>validate</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>
Note
The source formatter does not fundamentally change your code. For example, it will not change the order of import statements. It is effectively limited to adding or removing whitespace and line feeds.
Tip
You can use -Dspring-javaformat.validate.skip=true or -Dspring-javaformat.apply.skip=true command line arguments to temporarily skip the validation or format goals. If you want to skip both, you can use -Dspring-javaformat.skip=true.

Checkstyle

To enforce checksyle conventions add the checkstyle plugin and include a dependency on spring-javaformat-checkstyle:

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-checkstyle-plugin</artifactId>
			<version>3.1.1</version>
			<dependencies>
				<dependency>
					<groupId>com.puppycrawl.tools</groupId>
					<artifactId>checkstyle</artifactId>
					<version>9.3</version>
				</dependency>
				<dependency>
					<groupId>io.spring.javaformat</groupId>
					<artifactId>spring-javaformat-checkstyle</artifactId>
					<version>0.0.42</version>
				</dependency>
			</dependencies>
			<executions>
				<execution>
					<id>checkstyle-validation</id>
					<phase>validate</phase>
					<inherited>true</inherited>
					<configuration>
						<configLocation>io/spring/javaformat/checkstyle/checkstyle.xml</configLocation>
						<includeTestSourceDirectory>true</includeTestSourceDirectory>
					</configuration>
					<goals>
						<goal>check</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

Gradle

Source Formatting

For source formatting, add the spring-javaformat-gradle-plugin to your build plugins as follows:

buildscript {
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.42")
	}
}

apply plugin: 'io.spring.javaformat'

The plugin adds format and checkFormat tasks to your project. The checkFormat task is automatically applied when running the standard Gradle check task.

In case you want to exclude a package from being checked, for example if you generate sources, you can do this by adding following configuration:

tasks.withType(io.spring.javaformat.gradle.tasks.CheckFormat) {
    exclude "package/to/exclude"
}

Checkstyle

To enforce checksyle conventions add the checkstyle plugin and include a dependency on spring-javaformat-checkstyle:

apply plugin: 'checkstyle'

checkstyle {
	toolVersion = "9.3"
}

dependencies {
	checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.42")
}

Your checkstyle.xml file should look then like this:

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
		"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
		"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker">
	<module name="io.spring.javaformat.checkstyle.SpringChecks" />
</module>

Java 8 Support

By default, the formatter requires Java 17. If you are working on an older project, you can use a variation of the formatter based off Eclipse 2021-03 (the latest Eclipse JDT version built with Java 8).

To use the Java 8 version, add a file called .springjavaformatconfig to the root of your project with the following content:

java-baseline=8

Eclipse

The Eclipse plugin provides a custom formatter implementation and automatically applies project specific settings. The plugin is automatically activated whenever the Maven or Gradle plugins are discovered in a project build script.

If you need to customize the project specific settings that the plugin applies you should add a .eclipse folder in the root of your project. All .prefs files from this folder will be copied to the project .settings folders. Usually you’ll provide your own org.eclipse.jdt.core.prefs and org.eclipse.jdt.ui.prefs files.

You can also add a .eclipse/eclipse.properties file to customize the following items:

copyright-year= # The copyright year to use in new files

To install the plugin use the io.spring.javaformat.eclipse.site zip file. You can download the latest version from Maven Central or use the update site.

IntelliJ IDEA

The IntelliJ IDEA plugin provides custom formatter support for IntelliJ IDEA. The plugin is automatically activated whenever the Maven or Gradle plugins are discovered in a project build script or if a .springjavaformatconfig file. A Spring Java Format icon (formatOn) will also be displayed in the status bar to indicate the formatter is active. You can use the standard codereformat code action to format the code.

To install the plugin use the spring-javaformat-intellij-idea-plugin jar file. You can download the latest version from Maven Central.

Enable the Plugin

The plugin is automatically enabled when one or more of the following conditions match:

  • .springjavaformatconfig file exists

  • For a Maven-based project, spring-javaformat-maven-plugin plugin is defined in pom.xml

  • For a Gradle-based project, io.spring.javaformat plugin is applied

CheckStyle-IDEA plugin

The CheckStyle-IDEA plugin provides Checkstyle integration for IntelliJ IDEA.

To configure the plugin, create your own Checkstyle configuration file with the following content:

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
		"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
		"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker">
	<module name="io.spring.javaformat.checkstyle.SpringChecks" />
</module>

Once the configuration file is created, configure your IDE to use it:

  • Download spring-javaformat-checkstyle-0.0.42.jar from Maven Central.

  • Download spring-javaformat-config-0.0.42.jar from Maven Central.

  • Open Preferences - Tools - Checkstyle

  • Add spring-javaformat-checkstyle-0.0.42.jar and spring-javaformat-config-0.0.42.jar to the Third-Party Checks

  • Specify the appropriate Checkstyle version

  • Add and enable your Checkstyle configuration file

Visual Studio Code

The Visual Studio Code extension provides custom formatter support for Microsoft Visual Studio Code. The extension using the DocumentFormattingEditProvider API. Once installed it may be activated by using the “Format Document” action available in the editor context menu or from the Command Palette.

To install the extension select “Install from VSIX” in the extensions panel and choose the spring-javaformat-vscode-extension vsix file. You can download the latest version from Maven Central.

About the Conventions

Most of the coding conventions and style comes from the Spring Framework and Spring Boot projects. Spring Framework manually formats code, where as Spring Boot uses automatic formatting.

Indenting With Spaces

By default tabs are used for indenting formatted code. We strongly recommend that this default is not changed, especially for official Spring projects. If, however, you feel that you can’t live with tabs then switching to spaces is the one configuration option that we do support.

To use spaces rather than tabs, add a file called .springjavaformatconfig to the root of your project with the following content:

indentation-style=spaces

Tips

Formatting and Checkstyle alone are not enough to produce truly consistent code. Here are some tips that we’ve found useful when developing Spring Boot.

Excluding Specific Checks

If you want most SpringChecks but need to exclude one or two, you can do something like this in your checkstyle.xml:

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
		"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
		"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker">
	<module name="io.spring.javaformat.checkstyle.SpringChecks">
		<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringAvoidStaticImportCheck" />
	</module>
</module>

Disabling Formatting For Blocks of Code

Some code isn’t particularly amenable to automatic formatting. For example, Spring Security configurations often work better when manually formatted.

If you need to disable formatting for a specific block of code you can enclose it in a @formatter:off / @formatter:on set:

// @formatter:off

... code not be formatted

// @formatter:on

Wrapping

The source formatter uses 120 chars for wrapping. This aims to strike a balance between making use of available horizontal space in your IDE and avoiding unwanted additional wrapping when viewing code on GitHub and the like.

If you’re used to longer lines, 120 chars can take some getting used to. Specifically, if you have many nesting levels things can start to look quite bad. Generally, if you see code bunched up to the right of your screen you should take that as a signal to use the “extract method” refactor. Extracting small private methods will improve formatting and it helps when reading the code and debugging.

Whitespace

Keeping whitespace lines out of method bodies can help make the code easier to scan. If blank lines are only included between methods it becomes easier to see the overall structure of the class. If you find you need whitespace inside your method, consider if extracting a private method might give a better result.

Comments

Try to add javadoc for each public method and constant. Private methods shouldn’t generally need javadoc, unless it provides a natural place to document unusual behavior.

The checkstyle rules will enforce that all public classes have javadoc. They will also ensure that @author tags are well formed.

Final

Private members should be final whenever possible. Local variable and parameters should generally not be explicitly declared as final since it adds so much noise.

Read-down Methods, Fields and Parameters

Methods don’t need to be organized by scope. There’s no need to group all private, protected and public methods together. Instead try to make your code easy to read when scanning the file from top to bottom. In other words, try to have methods only reference method further down in the file. Keep private methods as close to the thing that calls them as possible.

It’s also recommend that you try to keep consistent ordering with fields and constructor parameters. For example:

class Name {

	private final String first;

	private final String last;

	public Name(String first, String last) {
		this.first = first;
		this.last = last;
	}

}

spring-javaformat's People

Contributors

boykoalex avatar cbot59 avatar dreis2211 avatar fabriziocucci avatar ganapathi004 avatar hccake avatar izeye avatar johanhammar avatar larsgrefer avatar leftstick avatar lorenzodee avatar malpi avatar mbhave avatar mhalbritter avatar parkerm avatar philwebb avatar rajadilipkolli avatar snicoll avatar spring-builds avatar spring-operator avatar tingstad avatar ttddyy avatar vpavic avatar wilkinsona avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spring-javaformat's Issues

Refine ternary rule

The (a != b ? c : d) is written in framework as (a != b) ? c : d which I think generally looks better. We should change our rule.

Allow this check customizations

Spring Framework needs some this. check customization support. Specifically they don't want this. for logger or from inner classes.

How to change "ImportOrderCheck" settings with custom checkstyle.xml?

How to change "ImportOrderCheck" settings with custom checkstyle.xml? It seems does not work.

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker">
	<module name="io.spring.javaformat.checkstyle.SpringChecks" >
	   <property name="headerType" value="unchecked"/>
	</module>
	<module name="com.puppycrawl.tools.checkstyle.TreeWalker">
	  <module name="com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck">
            <property name="groups" value="java,javax,com,org,*,com.websuites" />
            <property name="ordered" value="true" />
            <property name="separated" value="true" />
            <property name="option" value="bottom" />
            <property name="sortStaticImportsAlphabetically" value="true" />
          </module>
	</module>
</module>

Warning when using the maven plugin

Adding the Maven plugin to a project (initializr in this case) leads to

[WARNING] The POM for org.apache.maven.plugins:maven-eclipse-plugin:jar:2.1.0 is missing, no dependency information available
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-eclipse-plugin:2.1.0: Plugin org.apache.maven.plugins:maven-eclipse-plugin:2.1.0 or one of its dependencies could not be resolved: Failure to find org.apache.maven.plugins:maven-eclipse-plugin:jar:2.1.0 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced

Allow source folders to be excluded

Generates source files such as target/generated-sources/plugin/org/springframework/boot/maven/HelpMojo.java cannot easily be excluded currently because the exclude pattern only matches against org/springframework/boot/maven/HelpMojo.java. We need an easy way to exclude an entire folder.

TernaryCheck should allow if

introductionAwareMethodMatcher != null ? introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) : methodMatcher.matches(method, targetClass)

Checkstyle 8.11 fails with missing required CommonUtils class

Using the combination of io.spring.javaformat:spring-javaformat-checkstyle:0.0.5 and com.puppycrawl.tools:checkstyle:8.11 results in the following:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:check (checkstyle-validation) on project spring-cloud-deployer-openshift: Execution checkstyle-validation of goal org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:check failed: A required class was missing while executing org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:check: com/puppycrawl/tools/checkstyle/utils/CommonUtils
[ERROR] -----------------------------------------------------
[ERROR] realm =    plugin>org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
...
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import  from realm ClassRealm[maven.api, parent: null]]
[ERROR]
[ERROR] -----------------------------------------------------
[ERROR] : com.puppycrawl.tools.checkstyle.utils.CommonUtils

using the following plugin configuration:

...
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>3.0.0</version>
        <dependencies>
            <dependency>
                <groupId>com.puppycrawl.tools</groupId>
                <artifactId>checkstyle</artifactId>
                <version>8.11</version>
            </dependency>
            <dependency>
                <groupId>io.spring.javaformat</groupId>
                <artifactId>spring-javaformat-checkstyle</artifactId>
                <version>0.0.5</version>
            </dependency>
        </dependencies>
        <executions>
            <execution>
                <id>checkstyle-validation</id>
                <phase>validate</phase>
                <inherited>true</inherited>
                <configuration>
                    <configLocation>io/spring/javaformat/checkstyle/checkstyle.xml</configLocation>
                    <includeTestSourceDirectory>true</includeTestSourceDirectory>
                </configuration>
                <goals>
                    <goal>check</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
...

Provide an indication that the IDEA formatter is active

Hey,

I am using IntelliJ IDEA Ultimate 2018.1.4.

I have installed "spring-javaformat" plugin Version 1.0.

I added this to my parent pom.xm under build.plugins:

<plugin>
  <groupId>io.spring.javaformat</groupId>
  <artifactId>spring-javaformat-maven-plugin</artifactId>
  <version>0.0.3</version>
</plugin>

How do I know if the custom formatter is enabled? I do not see anything related to it unter Settings > Editor > Code Style > Java. It still says "Scheme: Default IDE".

Thanks!

Remove System.out trace

I've tried to upgrade Spring Initializr to 0.0.5 and just changing the version property leads to something like this:

[INFO] --- spring-javaformat-maven-plugin:0.0.5:validate (default) @ initializr-generator ---
[INFO]
[INFO] --- maven-checkstyle-plugin:3.0.0:check (checkstyle-validation) @ initializr-generator ---
PACKAGE_DEF -> package [17:0]
|--ANNOTATIONS -> ANNOTATIONS [17:17]
|--DOT -> . [17:17]
|   |--DOT -> . [17:10]
|   |   |--IDENT -> io [17:8]
|   |   `--IDENT -> spring [17:11]
|   `--IDENT -> initializr [17:18]
`--SEMI -> ; [17:28]
CLASS_DEF -> CLASS_DEF [24:0]
|--MODIFIERS -> MODIFIERS [24:0]
|   |--ANNOTATION -> ANNOTATION [24:0]
|   |   |--AT -> @ [24:0]
|   |   |--IDENT -> SuppressWarnings [24:1]
|   |   |--LPAREN -> ( [24:17]
|   |   |--EXPR -> EXPR [24:18]
|   |   |   `--STRING_LITERAL -> "serial" [24:18]
|   |   `--RPAREN -> ) [24:26]
|   `--LITERAL_PUBLIC -> public [25:0]
|--LITERAL_CLASS -> class [25:7]
|--IDENT -> InitializrException [25:13]
|--EXTENDS_CLAUSE -> extends [25:33]

(continued). I am a bit puzzled as where this is coming from so creating an issue here to investigate later.

Drop maven-eclipse plugin

We'd should drop the maven-eclipse plugin since it's no longer supported. We need to find a nice way to apply our own settings.

Eclipse plugin someomes doesn't indent correctly until save

I did extract variable on

	@Test
	public void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException() {
		this.thrown.expect(ConversionFailedException.class);
		this.conversionService.convert("ireallydontexist.example.com", InetAddress.class);
	}

and got

	@Test
	public void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException() {
		this.thrown.expect(ConversionFailedException.class);
		String missingDomain = "ireallydontexist.example.com";
this.conversionService.convert(missingDomain, InetAddress.class);
	}

Formatting can leave whitespace

Formatting

/**
 * Something.
 * @author Some One
 */

Results in

/**
 * Something.
 * 
 * @author Some One
 */

but there is trailing whitespace in the extra line.

Add ternary checkstyle rule

We should always write

(a != null ? b : c)

We should fail for

// missing parenthesis
a != null ? b : c

We should also fail for

// Checking == null rather than != null
(a == null ? b : c)

Wrong indentation in IntelliJ IDEA

When the plugin is active in IntelliJ IDEA, some live formatting are not working the same way as when the code is formatted.

Examples:

In builder style, the line will be too long so a new line should indent the code

Original code:

RestTemplate restTemplate = new RestTemplateBuilder().requestFactory(SimpleClientHttpRequestFactory::new).build();

If I invoke carriage return after the constructor (wrong):

RestTemplate restTemplate = new RestTemplateBuilder()
.requestFactory(SimpleClientHttpRequestFactory::new).build();

If I invoke the formatter manually (code reformat action in IJ) (correct):

RestTemplate restTemplate = new RestTemplateBuilder()
		.requestFactory(SimpleClientHttpRequestFactory::new).build();

A similar, yet slightly different, behaviour occurs with Javadoc

Original code:

/**
 * @author Stephane Nicoll
 */
public class Sample {
}

If the cursor is at the end of the first line (/**) and I invoke a carriage return, I get the following (wrong):

/**
* 
 * @author Stephane Nicoll
 */
public class Sample {
}

Again, invoking code reformat fixes it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.