简体   繁体   中英

Mapstruct with uses does not instantiate class

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: 在此处输入图像描述 The implementation for the mapper is generated. So why is drugstoreService null?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM