본문 바로가기

Back-end/Springboot

[SpringBoot] 롬복(Lombok)

롬복(Lombok)

모델 클래스를 생성할 때 반복적으로 사용하는 getter/setter 같은 메서드를 어노테이션으로 대체하는 기능을 제공하는 라이브러리이다. 

  • 장점
    • 어노테이션 기반으로 코드를 자동 생성하므로 생산성이 높아진다.
    • 반복되는 코드를 생략할 수 있어 가독성이 좋아진다.
    • 유지보수에 용이해진다.
  • 단점
    • 코드를 어노테이션이 자동 생성하기 때문에 메서드를 개발자의 의도대로 정확하게 구현하지 못한다.

1. 롬복 설치

pom.xml 파일에 롬복 의존성을 추가해준다.

<dependencies>
	...
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    ...
</dependencies>

plugin에서 Lombok 설치 확인

File -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors에 Enable annotation processing을 체크해준다.

 

2. 롬복 적용

- 적용 전

package com.springboot.jpa.data.entity;

import javax.persistence.*;
import java.time.LocalDateTime;

@Table(name="product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long number;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer price;

    @Column(nullable = false)
    private Integer stock;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    public Long getNumber() {
        return number;
    }

    public void setNumber(Long number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }
}

- 적용 후

package com.springboot.jpa.data.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name="product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long number;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer price;

    @Column(nullable = false)
    private Integer stock;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;
}

 

3. 롬복의 주요 어노테이션

  • @Getter, @Setter: 클래스에 선언돼 있는 필드에 대한 getter/setter 메서드를 생성한다.
  • @NoArgsConstructor: 매개변수가 없는 생성자를 자동 생성
  • @AllArgsConstructor: 모든 필드를 매개변수로 갖는 생성자를 자동 생성
  • @RequiredArgsConstructor: 필드 중 final이나 @NotNull이 설정된 변수를 매개변수로 갖는 생성자를 자동 생성
  • @ToString: toString() 메서드를 생성하는 어노테이션이다.
public String toString() {
        return "Product(number=" + this.getNumber() + ", name=" + this.getName() + ", price=" + this.getPrice() + ", stock=" + this.getStock() + ", createdAt=" + this.getCreatedAt() + ", updatedAt=" + this.getUpdatedAt() + ")";
    }
  • @EqualsAndHashCode(callSuper=false): callSuper 속성을 설정하여 부모 클래스의 필드를 비교 대상에 포함할 수 있다. false가 default 값
  • @Data: 앞서 설명한 어노테이션을 모두 포함한 어노테이션이다. 

 

 

 

참고 문헌: 스프링 부트 핵심 가이드(스프링 부트를 활용한 애플리케이션 개발 실무)

http://www.yes24.com/Product/Goods/110142898

 

스프링 부트 핵심 가이드 - YES24

입문자의 눈높이에 맞춰 차근차근 따라 하면서 배우는 스프링 부트 입문서!《스프링 부트 핵심 가이드》는 스프링 부트 기반의 애플리케이션을 개발할 때 필요한 기초적인 내용들을 소개하고,

www.yes24.com