Introduction to Lombok
In this article we are going to see how can we use lombok inside our regular Java Code to minimize code length & redundancy.
What is lombok?
Lombok , a compile time annotation pre-processor that helps to inject some code in compile time. Before going in detail, i request you should see the video from their site . I am not going live demo like this but I will show how we can use this inside project (including maven life cycle) .
Let’s start with basic understanding. As I have told, lombok is a compile time annotation pre-processor. What does that means?
- it will work in compile time (we can see effect during writing code)
- we need dependencies in class path during compilation (with javac command execution)
- We need to have plug-in support to see effect in IDE while coding.(as IDEs compiles during coding/saving)
Lombok has several Utility / feature . We will go through main items of them that I have used so far.
Note : To know about annotation , you may see my this post.
Installation :
Eclipse Installation:
Download from here, install it (you need to show eclipse installation directory)

(I have checked STS/eclipse Version: 3.7.3.RELEASE)
Intellij IDEA Installation:
Just install lombok plug-ins. (File -> Settings -> plugins -> search/brows to see, then install)
Or : Link of plugin
Enabling Annotation Processing
Now ,Based on IDE behavior, you may need to enable annotation preprocessor to let the plug-ins works. (usually modern IDE have this default)


Project setting up :
I will use Maven (you may use gradle in same manner) . My Maven version is 3.3.9.
Step 1 :
In pom.xml , add dependency
You may get updated version
Step 2:
As we see, lombok is a compile time pre processor, so, we need compiler. So, adding maven compiler plug-in inside build -> plugins->plugin
You can see, I have defined the source & target version to 1.8.
Step 3 :
Now we need to add lombok plugin for working during project compilation. For this we need entry in plugin Management and add plugin with parameters in build section.
- adding plugin with parameter
Notes :
- Encoding is necessary
- you can see I use 2 goals, these are spacial goals defined for lombok for test & source scope definition. I use both as my test code also needs lombok.
So, my Build section is become this.
And, for logging , we need to have dependencies. I will add all type of log example. So adding all of them together
So, finally my build section of POM
Now, its time to see Each feature Usages.
Notes :
For both eclipse and IntelliJ , I am using Outline View to look at the effects. To see outline tool window:
- Eclipse : Window -> Show view -> Outline
- IntelliJ: View -> Tool Buttons , you will structure.
@Getter @Setter : It heps to make getter setter with variable. It also supports access level parameters to define scopes of getters & setters.
Parameter : Takes a Enum parameter AccessLevel
- PUBLIC = Publicly accessible
- MODULE, PACKAGE = same as default (not using any modifier)
- PROTECTED = same as protected
- PRIVATE = same as private
- NONE = there will not be implementation


Overriding class level getter :

@ToString : This is implementation of toString(), we can use only for the class level. Parameters :
- includeFieldNames() : boolean type => define all field inclusion
- callSuper(): boolean type => calling super
- doNotUseGetters() : boolean type => avoid using getters of the fields.
- exclude() : String array of field names=> define field exclusion
- of() : String array of field names = > defines which to be added (explicitly)

@Data : It is combination of multiple annotations.
Where : We can use before a class /type
Parameters : @Data consists of
Example :


@Value : This is just an immutable value type of @Data.
Parameter : staticConstructor entry will make default constructor as private

@Builder : Adding a default builder class with your class. It is simply a builder (like builder pattern, with parameters, see example in image)
@Singular : For notifying a collection (support guava & java util only) . It include 2 adder methods, single add, add all.

val: This makes local final variable (inside method) (just immediate after this() or super() called) Usages :
- Use like as var(js/c#) , it will act as final
- Inside foreach loop.

@NotNull : This will add null check on variable and throws null pointer exception. Scope of use : method, parameter, local variable


@EqualsAndHashCode : It simple add equals(Object other), and hashCode() to class. (so it is class level annotation). It supports parameters to customize those equals and hash code methods. All parameters are same as @ToString. 
@Cleanup: It is an easy way to cleanup the resources. It actually ensures , the resources close() method will be called in finally block of try. Only Local variable :
Calling close method for resources. if you have another method name, then call you need value=thatMehtodName (like exit)
You can see a simple example from here. No need try catch.
In my opinion, it is nice to use this when you are not caring about managing resources. If you like to use your resources by your logic, better avoid this. Example, multi threaded resource usages.
Logging using lombok :
@log: This is one of the best usable feature. This picture shows all loggers to gather. My example in github will shows details.
We need to set log before class, that’s all. It will provide a static variable log and we can use it based on what type of log we are using.l
Parameter : it takes topic as parameter , by default it is class name. we can set log topic.

For different log implementation we need different type of configuration. Lombok doesn’t provide any configuration help, it just inject code. So, we need to add depend on what type of log I am adding. My example in github contains all 6 types of log configurations. See pom file carefully to know dependencies as well as resources for configuration files.
Source
There are lot more regular feature and experimental features I skipped due to not scope of my tests(spatially @Synchronized) . I will add other one by one.
Intro
I always heard comments from other developers things like: “Java is a very verbose language”, or Hello World line count comparison between Java vs Other X Language. And I also think that this is true, when you develop pure Java (without extensions, libs and plugins) compared to other modern languages, the developer ends up writing more to reach the goal. However, since some time ago, we have a lib called lombok that helps you simplify (a lot) the life of those who develop with java.
Features
Lombok is a lib that provides a collection of annotations that eases some repetitive java tasks (such as, getters and setters creation). Besides of being dependency of your project, it connects in your IDE making it understand the annotations, so it requires a certain configuration. In this guide I’ll show how to configure it on eclipse, intellij idea and also vscode. If you don’t know how to work with java with vscode take a look at: https://medium.com/daniel-padua/java-spring-boot-vscode-9ef9b8a263cd.
The github repository with the sample classes can be found at: https://github.com/danielpadua/lombok-examples
Requirements
- Java JDK 8 or higher
- Eclipse or IntelliJ IDEA or vscode
IDE configuration
Use the sections below according to the IDE you are using:
Eclipse
Download latest lombok.jar at: https://projectlombok.org/download, store this file in some directory of your choice (e.g.: your user’s home folder). From this moment on, there are two ways of configuring eclipse:
- Run the lombok.jar jar. It will open a window that will search in all folders of your machine looking for IDEs and if it finds eclipse it will display a checkbox to enable. So, click install and it will be done, as the image below:
2. If method 1 didn’t work or didn’t found any IDE, we will do the same work jar does under the hood but manually. Open the eclipse.ini file located under the configuration directory of the eclipse that you use, and edit it as below:
We are just adding the full path of lombok’s jar as eclipse’s initialisation argument, and this will make it understands lombok. Lombok’s jar does exactly the same thing, but it copies the jar inside of eclipse installation folder and writes eclipse.ini automatically.
IntelliJ IDEA
It’s really simple enable Lombok support in IntelliJ IDEA, to do so, open plugin installation section and install the highlighted plugin:
Restart IntelliJ IDEA and Lombok support will be enabled.
vscode
Search for lombok at the extensions tab:
Install the Gabriel Basilio Brito’s extension, which is recommended by lombok: https://projectlombok.org/setup/vscode. Restart vscode:
Project
First we need to create a java spring-boot project, so:
- To create a java spring-boot in eclipse follow this guide: https://medium.com/danielpadua/java-spring-boot-eclipse-744454468670
- To create a java spring-boot in intellij idea follow this guide: https://medium.com/danielpadua/java-spring-boot-intellij-idea-b919b0097a0
- To create a java spring-boot in vscode follow this guide: https://medium.com/danielpadua/java-spring-boot-vscode-f86562244fe1
After creating the project, use the sections below depending on the build-tool that you are using:
Maven
Add lombok’s dependency in pom.xml:
You may need to force maven import update on your IDE.
Gradle
Add lombok’s depedency in build.gradle file:
Usage
Now let’s explore what lombok has to offer for us to reduce boilerplate code:
Getters, Setters, Constructors, ToString, Equals e HashCode
To enable getter in all fields of your class, annotate above your class name: @Getter.
To enable setter in all fields of your class, annotate above your class name: @Setter.
To create a constructor with all fields as input parameter, annotate above your class name: @AllArgsConstructor, without parameters: @NoArgsConstrutor, with required fields (or non-null): @RequiredArgsConstructor
To implement default toString() use: @ToString,
To implement default equals() and hashCode() use: @EqualsAndHashCode
The @Data annotation above class is a shortcut to: @ToString, @EqualsAndHashCode, @Getter, @Setter and @RequiredArgsConstructor together.
Lombok – установка и настройка
Зачастую язык Java критикуют за излишнюю многословность – при объявлении класса приходится создавать геттеры и сеттеры для каждого необходимого поля, создавать конструкторы, переопределять методы toString, а также связку equals/hashCode. В современных IDE, конечно же, есть возможность всё это генерировать полуавтоматически, но необходимость заниматься шаблонным кодом всё равно никуда не исчезает. Проект Lombok призван бороться с этой проблемой.
Что такое Lombok
Lombok – это Java библиотека, призванная освободить разработчика от написания шаблонного кода. Lombok берёт на себя генерирование шаблонного кода по специальным аннотациям, которые указываются программистом в зависимости от того, какой код он хочет сгенерировать.
Установка Lombok
Установка состоит из двух этапов:
- Подключение библиотеки Lombok в проекте
- Установка плагина Lombok в IDE
Здесь мы будем использовать Maven и IntelliJ IDEA.
Подключение библиотеки Lombok в Maven
Добавьте в pom.xml следующую зависимость:
В случае, если вы используете Java 9 с module-info.java, добавьте следующую конфигурацию в pom.xml:

Последняя версия Lombok:
Установка плагина в IDEA
Откройте меню File → Settings → Plugins
В открывшемся окне плагинов введите «Lombok» в строке поиска а нажмите кнопку «Install»:

Подтвердите установку («Accept») и перезагрузите IDEA, чтобы плагин активировался.
Заключение
Мы вкратце рассмотрели основные возможности проекта Lombok. Также мыустановку библиотеки Lombok в качестве зависимости в проекте и плагина в IDE. В следующих статьях мы используем Lombok для того, чтобы уменьшить написание шаблонного кода.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Plugin for IntelliJ IDEA to support Lombok annotations.
Provides support for lombok annotations to write great Java code with IntelliJ IDEA.
Last version (0.34) released on 17.01.2021
Breaking News: Starting with IntelliJ version 2020.3 lombok plugin will be integrated and included in IntelliJ by default!.
Enjoy new kind of experience for lombok support inside of IntelliJ Idea!
️ Previous InteliJ versions still supported by corresponding plugin version!
37th version of plugin released.
Install it automatically from IntelliJ Idea plugin repository.
Tested and supports IntelliJ versions: 2018.X, 2019.X, 2020.1 and 2020.2.1+, 2020.3 (Build In!)
Last support for IntelliJ 2017.1, 2017.2 and 2017.3 by plugin version 0.32!
Last support for IntelliJ 2016.2 and 2016.3 by plugin version 0.31!
Last support for IntelliJ 15.0.6 and 2016.1 by plugin version 0.19!
Last support for IntelliJ 14.1.7 by plugin version 0.14!
Last support for IntelliJ 11.1.5, 12.1.7, 13.1.6 by plugin version 0.11
Last support for IntelliJ 10.5.4 by plugin version 0.8.7
With this plugin your IntelliJ can recognize all of generated getters, setters and some other things from lombok project, so that you get code completion and are able to work without errors stating the methods don’t exists.
Many features of the plugin (including warnings) could be disabled through per-project settings.
- Using IDE built-in plugin system on Windows:
- File > Settings > Plugins > Browse repositories. > Search for «lombok» > Install Plugin
- Preferences > Settings > Plugins > Browse repositories. > Search for «lombok» > Install Plugin
- Download the latest release and install it manually using Preferences > Plugins > Install plugin from disk.
Required IntelliJ Configuration
In your project: Click Preferences -> Build, Execution, Deployment -> Compiler, Annotation Processors . Click Enable Annotation Processing
Afterwards you might need to do a complete rebuild of your project via Build -> Rebuild Project .
Lombok project dependency
Make sure you have Lombok dependency added to your project. This plugin does not automatically add it for you.
Please Note: Using newest version of the Lombok dependency is recommended, but does not guarantee that all the features introduced will be available. See Lombok changelog for more details.