Eclipse Tip - Format Source Code on Save

Posted on Sep 18, 2014 (last modified Jun 1, 2021)

Pressing CTRL + SHIFT + F in the Eclipse editor will automatically format source code according to the default or specific formatter preference settings. However, if team members do not format consistently before committing code, relevant changes can become difficult to identify amongst code style changes. One way to alleviate this problem is to force Eclipse (or any Eclipse-based IDE) to format source code automatically on Save. Here’s how…

You can set this behavior globally or on a per-project basis. I would recommend that you enforce it at the project level since you can’t be sure that other developers will keep the global setting turned on. This will work in Eclipse or any Eclipse-based IDE such as Rational Application Developer or the Spring Tools Suite.

Project specific settings

  1. Right-click on any project in the workspace and select Properties.
  2. In the Project Properties dialog, expand Java Editor and then click Save Actions.
  3. Check Enable project specific settings.
  4. Check Format source code and Organize imports.
  5. Click Apply and OK.

Global settings

  1. Select Window > Preferences in the application menu.
  2. In the Preferences dialog, expand Java > Editor and then click on Save Actions.
  3. Check Perform the selected actions on save.
  4. Check Format source code and Organize imports.
  5. Click Apply and OK.