MapStruct 적용기

Walter Mitty·2023년 5월 26일
0
post-thumbnail

회사에서 Dto 에서 ResponseDto로 데이터를 담아야하는 상황이 있었는데,
원래 처럼 Builder를 사용해서 넣어주다가 Builder 자체도 어쨌든 Setter 역할을 하기 때문에 지양해야한다는 얘기를 들었다.
그래서 사수분이 코드리뷰를 하면서 두가지 방법을 추천해주셨다.

  1. ModelMapper
  2. MapStruct

NCloud에서 제공해준 참고자료

먼저 나는 Gradle 을 통해 빌드를 하고 있어서 build.gradle에 Dependency를 넣어주었다.

dependencies {
    ...
    implementation 'org.mapstruct:mapstruct:1.5.3.Final'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.3.Final'
    ...
}

🚨 주의 🚨 MapStruct는 Lombok의 getter, setter, builder를 이용하여 생성되므로 Lombok보다 먼저 dependency가 선언 되는 경우 정상적으로 실행할 수 없다.
따라서 꼭! cmd+f 로 Lombok 을 검색해서 그 아래에 선언해주자.
그리고 나서 코리끼모양 build 를 클릭해서 잘 실행되는지 확인!

1.

경우가 세가지인데 차차 정리 예정.


Bean으로 등록하기

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 3 of constructor in com.kaii.mdm.application.faq.FaqApplicationService required a bean of type 'com.kaii.mdm.presentation.faq.response.FaqMapper' that could not be found.


Action:

Consider defining a bean of type 'com.kaii.mdm.presentation.faq.response.FaqMapper' in your configuration.


Process finished with exit code 0

오랜만이군요.
Bean으로 등록해주자.

등록 전 code

@Mapper
public interface FaqMapper {
    FaqMapper INSTANCE = Mappers.getMapper(FaqMapper.class);

    // FaqDto를 FaqInfoResponse 로 매핑
    FaqInfoResponse toFaqInfoResponse(FaqDTO faqDTO);
}

등록 후 code

Mapper용 interface를 찾아서 @Mapper 어노테이션 옆에 (componentModel = "spring") 를 붙여주자!

@Mapper(componentModel = "spring") // 바로 요부분!
public interface FaqMapper {
    FaqMapper INSTANCE = Mappers.getMapper(FaqMapper.class);

    // FaqDto를 FaqInfoResponse 로 매핑
    FaqInfoResponse toFaqInfoResponse(FaqDTO faqDTO);
}

0개의 댓글