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
- Right-click on any project in the workspace and select Properties.
- In the Project Properties dialog, expand Java Editor and then click Save Actions.
- Check Enable project specific settings.
- Check Format source code and Organize imports.
- Click Apply and OK.
Global settings
- Select Window > Preferences in the application menu.
- In the Preferences dialog, expand Java > Editor and then click on Save Actions.
- Check Perform the selected actions on save.
- Check Format source code and Organize imports.
- Click Apply and OK.