티스토리 뷰

Spring

[Spring] 스프링(Spring)과 롬복(Lombok)의 결합, @RequiredArgsConstructor를 사용한 생성자 주입

망나니개발자 2021. 5. 20. 23:09
반응형

1. 롬봄(Lombok)에 대한 이해와 활용


[ 롬봄(Lombok) 이란? ]

Lombok이란 어노테이션 기반으로 코드를 자동완성 해주는 라이브러리이다. Lombok을 이용하면 Getter나 Setter, 생성자 등을 자동완성 시킬 수 있어서 개발자의 생산성을 높여준다.

(Lombok에 대해 자세한 내용은 여기를 참고해주세요!)

@Getter
@Setter
public class User {

    private String email;
    private String name;

}

 

 

[ @RequiredArgsConstructor ]

Lombok의 다양한 어노테이션들 중에서 이번에 주목해 볼 것은 @RequiredArgsConstructor 이다. 이 어노테이션은 NotNull이거나 final이 붙은 변수들에 대해 생성자를 만들어주는 기능을 제공하고 있다.

@RequiredArgsConstructor
public class User {

    private final String email;
    private final String name;

   /* 이 생성자를 자동으로 만들어줌
   public User(String email, String name) {
        this.email = email;
        this.name = name;
   }
   */

}

 

그리고 @RequiredArgsConstructor은 final 변수와 생성자 주입을 권장하는 Spring 프레임워크와 찰떡궁합을 보여주고 있는데, 어떻게 두 기술이 서로 조합을 이루는지 알아보도록 하자.

 

 

 

2. 스프링(Spring)과 롬복(Lombok)의 결합, @RequiredArgsConstructor를 사용한 생성자 주입


[ Spring 프레임워크와 롬복(Lombok)의 결합 ]

1. Spring 프레임워크를 통한 생성자 주입

Spring 프레임워크는 생성자 주입을 권장하고 있는데, 일반적으로 다음과 같이 구현해야 한다.

@Service
public class UserService {

    private UserRepository userRepository;
    private PasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

}

 

 

2. final 키워드와의 결합

하지만 위와 같은 생성자 주입은 개선할 여지가 있어 보인다. 왜냐하면 UserRepsotiory와 PasswordEncoder과 같은 빈들은 Spring 컨테이너가 관리하는 싱글톤 객체이기 때문에 변하지 않기 때문이다. 그래서 해당 빈(Bean) 들이 생성자를 통해 주입되는 시점에 불변성을 보장하도록 final 키워드를 붙여주는 것이 좋다.

@Service
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

}

 

 

 

3. Lombok(롬복)과의 결합

위와 같은 생성자 주입 코드를 모든 빈마다 생성하려면 상당히 번거로울 것이다. 또한 새로운 빈을 생성자 주입으로 추가하는 과정도 번거롭다. 이때 Lombok 라이브러리는 이를 간소화할 수 있도록 도와주는데, 이 과정에서 Spring 프레임워크의 도움이 있다.

Spring 프레임워크는 1개 뿐인 생성자에 대해서 @Autowired가 없을 경우 @Autowired를 자동으로 인식하여 처리한다. 즉, 생성자가 1개뿐이라면 @Autowired를 생략해도 된다는 것이다. (이것은 Spring4.3부터 제공하는 기능이다.)

@Service
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    // @Autowired --> 생성자가 1개라면 생략 가능
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

}

 

 

그러면 이제 우리는 @Autowired 필요 없이 1개의 생성자만을 만들어주면 된다. 그리고 이때 Lombok 라이브러리를 사용하면 생성자 주입 코드를 간소화할 수 있는 것이다.

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

}

 

 

Lombok라이브러리를 통해 생성자를 생성하면, Spring 프레임워크는 해당 생성자에 @Autowired가 생략되었다고 인식하고, 적합한  Spring 빈들을 주입해준다. 이러한 Spring 프레임워크의 숨겨진 도움이 있었기 때문에 우리는 Lombok을 통해 생성자 주입을 아주 편리하게 이용할 수 있는 것이다.

 

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함