微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将映射添加到模型映射器的问题

如何解决将映射添加到模型映射器的问题

我在将具有自定义 PropertyMap 定义的类添加到模型映射器时遇到了问题。只要我在我正在使用的类的 @postconstruct添加了映射,一切都在工作。另一方面,当我将它移动到我想要添加所有 PropertyMap 的新类时,似乎没有添加到模型映射器中。

使用此配置,一切正常。 RestCompanyDto 有对象 RestAddressDto,当我使用模型映射器的映射函数时,内部对象被正确转换。

@Service
@requiredArgsConstructor
public class RestOrganizationService {


    private final modelmapper modelmapper;
    private final RestAddressDtoMap addressDtoMap;
    

    @postconstruct
    public void mapperConfig() {
        modelmapper.addMappings(addressDtoMap);
    }

    private OfficeDto map(Long id,RestOfficeDto restOfficeDto){
        OfficeDto officeDto = modelmapper.map(restOfficeDto,OfficeDto.class);
        officeDto.setId(id);
        return officeDto;
    }

另一方面,当我从 RestOrganizationService 中删除 @postconstructor 并将其移动到新类时,地址对象的映射不起作用。

@配置

@AllArgsConstructor
public class EPRestMapperConfig {
    private final modelmapper modelmapper;
    private final RestAddressDtoMap restAddressDtoMap;

    @postconstruct
    public void init() {
        modelmapper.addMappings(restAddressDtoMap);
    }
}

这是PropertyMap的附加代码

@Service
public class RestAddressDtoMap extends PropertyMap<RestAddressDto,AddressDto> {

    private CityRepository cityRepository;
    private CityServiceImpl cityService;

    public RestAddressDtoMap(CityRepository cityRepository,CityServiceImpl cityService){
        super(RestAddressDto.class,AddressDto.class);
        this.cityRepository = cityRepository;
        this.cityService = cityService;
    }

    @Override
    protected void configure() {
        using(getCityDto).map(source.getCityId()).setCity(null);
    }


    private final Converter<Long,CityDto> getCityDto = context ->
            (context.getSource() != null
                    ? cityService.toDto(cityRepository.findOne(context.getSource()))
                    : null);


}

解决方法

在你的情况下,我建议使用以下方法:

@Configuration
public class EPRestMapperConfig {
    @Bean
    public ModelMapper modelMapper(RestAddressDtoMap restAddressDtoMap) {
        return new ModelMapper().addMappings(restAddressDtoMap);
    }

    @Bean
    public RestAddressDtoMap restAddressDtoMap() {
        return new RestAddressDtoMap();
    }
}

我喜欢这种创建 bean 的风格,因为您可以在 bean 创建过程中看到 bean 之间所需的依赖关系并设置所需的组件。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。