'How to using mapstruct and springboot bean together? @autowired
@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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Georgii Lvov |
