Java Lombok Overview

What Is Lombok?

  • When you declare annotations, Lombok automatically generates repetitive code such as getter, setter, toString, and equals at compile time.
  • However, generating getters and setters without care can also undermine object-oriented design.
  • For that reason, unless a framework you use requires getters and setters and there is no practical alternative, it may be better not to use them casually.

Environment Setup

Depending on the tool, Lombok may require a separate plugin installation or configuration. Recent versions of IntelliJ IDEA, for example, can run Lombok with configuration only, without installing a separate plugin. Check the installation method for each tool and configure it accordingly.

Hello World

Write build.gradle as follows.

plugins {
    id 'java'
}

group 'com.devkuma'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'

    compileOnly 'org.projectlombok:lombok:1.18.20'
    annotationProcessor 'org.projectlombok:lombok:1.18.20'

    testCompileOnly 'org.projectlombok:lombok:1.18.20'
    testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
}

Create a HelloLombokTutorial.java file and write the code as follows.

package com.devkuma.tutorial.lombok;

import lombok.Data;

@Data
public class HelloLombokTutorial {

    private String string;
    private int number;
    
    public static void main(String[] args) {
        HelloLombokTutorial tutorial = new HelloLombokTutorial();

        tutorial.setString("Hello Lombok!!");
        tutorial.setNumber(999);

        System.out.println(tutorial);
    }
}

Execution result:

Main(string=Hello Lombok!!, number=999)
  • By declaring the @Data annotation on the class, methods such as getter, setter, and toString were generated automatically.
  • Lombok itself is used only at compile time, so set its dependency scope to compileOnly.

References