Mapstruct with uses does not instantiate class

Viewed 410

I have the following Mapper:

@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 is an interface with the following implementation:

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

When trying to use the mapper, a NullPointerException is thrown because DrugstoreService is not instantiated in the mapper's implementation. Here is a screenshot from debugging the code: enter image description here The implementation for the mapper is generated. So why is drugstoreService null?

1 Answers

When using componentModel different then the default one you have to use the appropriate dependency injection framework to instantiate your mappers. In your case you have to use Spring to get your mapper and not instantiate it manually.

Related