我找了很久也没找到解决这个问题的方法。在我的 spring 应用程序中,我有一个 BesoinPoseMapper
@FunctionalInterface
@Mapper(uses = BesoinPoseTranslator.class)
public interface BesoinPoseMapper {
@Mappings({
@Mapping(target = "nbCapteurs", source = "valeur", qualifiedByName = {"BesoinPoseTranslator", "nbCapteurs"}),
@Mapping(target = "typologie", source = "typologie", qualifiedByName = {"BesoinPoseTranslator", "typologie"}),
@Mapping(target = "site", source = "site", qualifiedByName = {"BesoinPoseTranslator", "emplacement"})
})
BesoinPoseDTO entityToDTO(BesoinPoseEntity entity);
}
将 BesoinPoseEntity
映射到 BesoinPoseDTO
但是BesoinPoseController
中的 map 函数
public class BesoinPoseController {
@Setter
@Autowired
private BesoinPoseRepository besoinPoseRepo;
@GetMapping()
public List<BesoinPoseDTO> getBesoinsPose(@RequestParam String range, @RequestParam(required = false) String status){
return StreamSupport.stream(besoinPoseRepo.findAll().spliterator(), false)
.map(BesoinPoseMapper::entityToDTO)
.collect(Collectors.toList());
}
}
抛出编译错误
.map(BesoinPoseMapper::entityToDTO);
^
required: Function<? super BesoinPoseEntity,? extends R>
found: BesoinPose[...]ToDTO
reason: cannot infer type-variable(s) R
(argument mismatch; invalid method reference
cannot find symbol
symbol: method entityToDTO(BesoinPoseEntity)
location: interface BesoinPoseMapper)
where R,T are type-variables:
R extends Object declared in method <R>map(Function<? super T,? extends R>)
T extends Object declared in interface Stream
我尝试使用 lambda 并将类型从可迭代更改为列表和数组,然后返回流,但无济于事,错误仍然存在。编译器无法推断 R 类型是 BesoinPoseDTO
。
有办法解决这个问题吗?
谢谢
最佳答案
一旦生成映射器的实现,您需要创建一个 BesoinPoseMapper
实例,换句话说,这是实例的入口点,如下所示:
@Mapper(uses = BesoinPoseTranslator.class)
public interface BesoinPoseMapper {
BesoinPoseMapper INSTANCE = Mappers.getMapper(BesoinPoseMapper.class);
//...
}
现在在您的组件中您可以使用:
.map(BesoinPoseMapper.INSTANCE::entityToDTO);
或:
private BesoinPoseMapper besoinPoseMapper = BesoinPoseMapper.INSTANCE;
...
.map(besoinPoseMapper::entityToDTO);
Spring
或者因为您使用的是 spring,您可以使用 componentModel = "spring"
:
@Mapper(uses = BesoinPoseTranslator.class, componentModel = "spring")
然后您可以将映射器作为任何 Spring 组件注入(inject)到您的组件中,例如:
@Autowired
private BesoinPoseMapper besoinPoseMapper;
关于Java spring map 无法推断类型变量 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65018195/