java—向模型Map器添加Map的问题

4ktjp1zp  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(420)

我在向模型Map器添加定义为CustomPropertyMap的类时遇到了问题。只要将Map添加到我正在使用的类的@postconstruct中,一切都正常。另一方面,当我将这个类移到新类中时,我希望添加所有属性Map,但似乎没有添加到模型Map器。
在这种配置下,一切正常。restcompanydto有对象restaddressdto,当我使用模型Map器的Map函数时,内部对象被正确地转换。

@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并将其移动到新类时,address对象的Map不起作用。
@Configuration

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

}
az31mfrm

az31mfrm1#

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

@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之间所需的依赖关系并设置所需的组件。

相关问题