具有使用功能的Mapstruct不会实例化类

问题描述 投票:3回答:1

我有以下映射器:

@Mapper(componentModel="spring", uses = {DrugstoreService.class})
public abstract class PreregisteredPharmacistMapper {

    @Mapping(source = "drugstoreId", target = "drugstore")
    public abstract PreregisteredPharmacist toEntity (
            PreregisteredPharmacistDTO preregisteredPharmacistDTO
    );

    public abstract void toEntityUpdate (
            @MappingTarget PreregisteredPharmacist preregisteredPharmacist,
            PreregisteredPharmacistDTO preregisteredPharmacistDTO
    );

    public abstract PreregisteredPharmacistDTO toDTO(
            PreregisteredPharmacist preregisteredPharmacist
    );
}

DrugstoreService是具有以下实现的接口:

@Service
public class DrugstoreServiceImpl implements DrugstoreService {

    private DrugstoreRepository drugstoreRepository;

    /**
     * DrugstoreServiceImpl constructor.
     *
     * @param drugstoreRepository
     */
    @Autowired
    public DrugstoreServiceImpl (
            DrugstoreRepository drugstoreRepository
    ) {
        this.drugstoreRepository = drugstoreRepository;
    }

    @Override
    public Drugstore findEntityById(Integer id) {
        Optional<Drugstore> drugstore = drugstoreRepository.findById(id);
        if (!drugstore.isPresent()) {
            throw new ResourceNotFoundException("Drugstore", "id", id);
        }

        return drugstore.get();
    }
}

[尝试使用映射器时,由于未在映射器的实现中实例化DrugstoreService,所以抛出NullPointerException。这是调试代码的屏幕截图:enter image description here映射器的实现已生成。那么为什么DrugstoreService为null?

java spring-boot autowired mapstruct
1个回答
0
投票
当使用componentModel时,与默认值不同时,您必须使用适当的依赖项注入框架来实例化您的映射器。在您的情况下,您必须使用Spring来获取您的映射器,而不是手动实例化它。
© www.soinside.com 2019 - 2024. All rights reserved.