Spring/스프링 핵심 원리 - 기본편

43. 롬복과 최신 트랜드 (@RequiredArgsConstructor)

DEV-HJ 2023. 5. 7. 17:12
반응형

롬복과 최신 트랜드

막상 개발을 해보면, 대부분이 다 불변이고, 그래서 다음과 같이 필드에 final 키워드를 사용하게 된다.
그런데 생성자도 만들어야 하고, 주입 받은 값을 대입하는 코드도 만들어야 하고…
필드 주입처럼 좀 편리하게 사용하는 방법은 없을까?
역시 개발자는 귀찮은 것은 못 참는다! 다음 기본 코드를 최적화해보자.

 

기본 코드

@Component
public class OrderServiceImpl implements OrderService {

	private final MemberRepository memberRepository;
	private final DiscountPolicy discountPolicy;

	@Autowired
	public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
		this.memberRepository = memberRepository;
		this.discountPolicy = discountPolicy;
	}
}

 

 

생성자가 딱 1개만 있으면 @Autowired 를 생략할 수 있다

@Component
public class OrderServiceImpl implements OrderService {

	private final MemberRepository memberRepository;
	private final DiscountPolicy discountPolicy;

	public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
		this.memberRepository = memberRepository;
		this.discountPolicy = discountPolicy;
	}
}
  • 이제 롬복을 적용해보자. 롬복 라이브러리 적용 방법은 아래에 적어두었다.
  • 롬복 라이브러리가 제공하는 @RequiredArgsConstructor 기능을 사용하면 final이 붙은 필드를 모아서
    생성자를 자동으로 만들어준다. (다음 코드에는 보이지 않지만 실제 호출 가능하다.)
  • 최종 결과는 다음과 같다! 정말 간결하지 않은가!

 

최종 결과 코드

@Component
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
	
    private final MemberRepository memberRepository;
	private final DiscountPolicy discountPolicy;
}
  • 이 최종결과 코드와 이전의 코드는 완전히 동일하다. 롬복이 자바의 애노테이션 프로세서라는 기능을
    이용해서 컴파일 시점에 생성자 코드를 자동으로 생성해준다.
  • 실제 class 를 열어보면 다음 코드가 추가되어 있는 것을 확인할 수 있다
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
		this.memberRepository = memberRepository;
		this.discountPolicy = discountPolicy;
}

정리

  • 최근에는 생성자를 딱 1개 두고, @Autowired 를 생략하는 방법을 주로 사용한다. 여기에 Lombok
  • 라이브러리의 @RequiredArgsConstructor 함께 사용하면 기능은 다 제공하면서, 코드는 깔끔하게
    사용할 수 있다

롬복 라이브러리 적용 방법


build.gradle 에 라이브러리 및 환경 추가

plugins {
	id 'org.springframework.boot' version '2.3.3.RELEASE'
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
}
group = 'hello'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

// lombok 설정 추가 시작
configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}
// lombok 설정 추가 끝

repositories {
	mavenCentral()
}
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter'

	//lombok 라이브러리 추가 시작
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testCompileOnly 'org.projectlombok:lombok'
	testAnnotationProcessor 'org.projectlombok:lombok'
	//lombok 라이브러리 추가 끝

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}
test {
	useJUnitPlatform()
}
  1. Preferences(윈도우 File  → Settings) plugin lombok 검색 설치 실행 (재시작)
  2. Preferences →  Annotation Processors 검색 Enable annotation processing 체크 (재시작)
  3. 임의의 테스트 클래스를 만들고 @Getter, @Setter 확인
반응형