我有以下映射器:
@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 是一个具有以下实现的接口(interface):
@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();
}
}
尝试使用映射器时,会引发 NullPointerException,因为 DrugstoreService 未在映射器的实现中实例化。
这是调试代码的屏幕截图:
生成映射器的实现。那么为什么 drugstoreService 为空呢?
最佳答案
使用 componentModel
时与默认的不同,您必须使用适当的依赖注入(inject)框架来实例化您的映射器。在您的情况下,您必须使用 Spring 来获取您的映射器,而不是手动实例化它。
关于java - 使用的 Mapstruct 不实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154745/