How to using mapstruct and springboot bean together? @autowired
Asked Answered
M

1

9
@Mapper(componentModel = "spring")
public interface DemoConvert {
    public static DemoConvert INSTANCE = mappers.getMapper(DemoConvert.class);

    @AutoWired
    private PersonInfoSearchService personInfoSearchService;

    @Mapping(source = "name", target = "name")
    @Mapping(source = "id", target = "gender", expression = "java(personInfoSearchService.searchGenderById(id))")
    PersonDTO toPerson(TeacherDTO teacherDTO);
}

How to using mapstruct and springboot bean together? @autowired

Midday answered 4/2, 2022 at 7:4 Comment(0)
B
19

You need to change the interface to an abstract class and move PersonInfoSearchService call to @Named method:

@Mapper(componentModel = "spring")
public abstract class DemoConvert {

    @Autowired
    private PersonInfoSearchService personInfoSearchService;

    
    @Mapping(source = "name", target = "name")
    @Mapping(source = "id", target = "gender", qualifiedByName = "mapGenderFromId")
    public abstract PersonDTO toPerson(TeacherDTO teacherDTO);


    @Named("mapGenderFromId")
    String mapGenderFromId(Long id) { // return type of gender, I took String. For id took Long
        return personInfoSearchService.searchGenderById(id);
    }
}

Besides you don't need to declare an INSTANCE variable, since you're using componentModel = "spring". You can simple autowire your mapper into other spring beans.

Buchanan answered 4/2, 2022 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.