java Mapstruct是否能够将源对象传递给@AfterMapping方法?

i34xakig  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(132)

考虑一下这段代码

@Mapper
@RequiredArgsConstructor
public abstract class QuestionCommentMapper {
    protected final QuestionService questionService;

    public abstract QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto,
                                                                          @Context Authentication auth);

    @AfterMapping
    protected void enrichWithOwner(@MappingTarget QuestionComment questionComment, @Context Authentication auth) {
        Account owner = AuthenticationProcessor.extractAccount(auth);
        questionComment.setOwner(owner);
    }

    @AfterMapping
    protected void enrichWithQuestion(@MappingTarget QuestionComment questionComment,
                                      @Context QuestionCommentRequestDto dto) {
        Long questionId = dto.questionId();
        Question question = questionService.getById(questionId);
        questionComment.setQuestion(question);
    }
}

**Mapstruct是否会将QuestionCommentRequestDto对象传递给enrichWithQuestion()方法,该方法是原始Map方法中的源?如果没有,我如何在不放弃Mapstruct的代码生成的情况下执行第二次“丰富”?**如果我在Map方法中写入任何内容(例如使用QuestionCommentRequestDto示例来设置QuestionCommentQuestion字段,就像在我的enrichWithQuestion()方法中一样),Mapstruct不会生成任何内容,我基本上必须手动编写所有内容

0sgqnhkj

0sgqnhkj1#

看起来Mapstruct * 是 * 有能力的,不需要额外的代码。下面是生成的方法

@Override
    public QuestionComment dtoAndAuthenticationToQuestionComment(QuestionCommentRequestDto dto, Authentication auth) {
        if ( dto == null ) {
            return null;
        }

        QuestionComment questionComment = new QuestionComment();

        questionComment.setText( dto.text() );

        enrichWithOwner( questionComment, auth );
        enrichWithQuestion( questionComment, dto ); // ← look at it

        return questionComment;
    }

让我提出这个问题的主要原因是一个聊天机器人说Mapstruct不会传递源对象,因为
常规Map方法中使用的任何源参数都不会传递给@AfterMapping方法,因为此时任何进一步的Map操作都不需要它们。
看来聊天机器人搞错了

相关问题