Java 使用的Mapstruct不会实例化类
我有以下映射器:Java 使用的Mapstruct不会实例化类,java,spring-boot,autowired,mapstruct,Java,Spring Boot,Autowired,Mapstruct,我有以下映射器: @Mapper(componentModel="spring", uses = {DrugstoreService.class}) public abstract class PreregisteredPharmacistMapper { @Mapping(source = "drugstoreId", target = "drugstore") public abstract PreregisteredPharmacist toEntity (
@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();
}
}
@服务
公共类DrugstoreServiceImpl实现DrugstoreService{
私人药店储存库;
/**
*DrugstoreServiceImpl构造函数。
*
*@param drugstoreRepository
*/
@自动连线
公共药店(
药店储存库药店储存库
) {
this.drugstoreRepository=drugstoreRepository;
}
@凌驾
公共药店FindentialById(整数id){
可选药店=drugstoreRepository.findById(id);
如果(!drugstore.isPresent()){
抛出新的ResourceNotFoundException(“药店”、“id”、id);
}
返回药店;
}
}
尝试使用映射器时,会引发NullPointerException,因为映射器的实现中未实例化DrugstoreService。
以下是调试代码的屏幕截图:
将生成映射器的实现。那么为什么drugstoreService为空呢?当使用组件模型时,您必须使用适当的依赖项注入框架来实例化映射程序。在您的情况下,您必须使用Spring来获取映射器,而不是手动实例化它。我建议针对MapStruct提交bug,原因有两个:依赖项应该声明为接口类型
DrugstoreService
,生成器应该使用构造函数注入。(请记住,这里和那里的代码都是文本,而不是屏幕截图。)