Reputation: 378
@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
Upvotes: 10
Views: 18970
Reputation: 2701
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.
Upvotes: 22