【问题标题】:How to using mapstruct and springboot bean together? @autowired如何一起使用mapstruct和springboot bean? @autowired
【发布时间】:2022-02-04 07:04:29
【问题描述】:
@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);
}

如何同时使用 mapstruct 和 springboot bean? @autowired

【问题讨论】:

    标签: java spring-boot javabeans autowired mapstruct


    【解决方案1】:

    您需要将接口更改为抽象类并将PersonInfoSearchService调用移动到@Named方法:

    @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);
        }
    }
    

    此外,您不需要声明INSTANCE 变量,因为您使用的是componentModel = "spring"。您可以简单地将映射器自动装配到其他 Spring bean。

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 2018-03-06
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      相关资源
      最近更新 更多