我有下一个映射器:
@Mapper
@Component
public interface PriceEntityMapper {
@Mapping(source="brandId", target="brandId")
@Mapping(source="startDate", target="startDate", qualifiedByName = "timestampToLocalDateTime")
@Mapping(source="endDate", target="endDate", qualifiedByName = "timestampToLocalDateTime")
@Mapping(source="priceList", target="priceList")
@Mapping(source="productId", target="productId")
@Mapping(source="priority", target="priority")
@Mapping(source="price", target="price")
@Mapping(source="curr", target="currency")
Price priceEntityToPrice(PriceEntity priceEntity);
@Named("timestampToLocalDateTime")
default LocalDateTime timestampToLocalDateTime(Timestamp timestamp) {
return timestamp.toLocalDateTime();
}
}
以及下一个实施:
@Service
public class PriceServiceImpl implements PriceService {
private final PriceRepository priceRepository;
private final PriceEntityMapper priceEntityMapper;
@Autowired
public PriceServiceImpl(PriceRepository priceRepository, PriceEntityMapper priceEntityMapper) {
this.priceRepository = priceRepository;
this.priceEntityMapper = priceEntityMapper;
}
@Override
public Price getPrice(LocalDateTime applicationDate, Integer productId, Integer brandId) {
try {
//PriceEntity priceEntity = priceRepository.findByBrandIdAndProductIdAndStartDateLessThanEqualApplicationDateAndEndDateGreaterThanEqualApplicationDate(brandId, productId, Timestamp.valueOf(applicationDate));
return priceEntityMapper.priceEntityToPrice(new PriceEntity());
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Price not found", e);
}
}
}
好吧,当我尝试运行该应用程序时,出现下一个错误:
com.dharian.application.service.PriceServiceImpl 中构造函数的参数 1 需要类型为“com.dharian.infraestruct.mapper.PriceEntityMapper”的 bean,但无法找到。
但是我有注释
@Mapper
和@Component
,我也有
@SpringBootApplication
@ComponentScan({"com.dharian.infraestructure", "com.dharian.application"})
public class PruebatecnicaApplication {
public static void main(String[] args) {
SpringApplication.run(PruebatecnicaApplication.class, args);
}
}
用于扫描包裹。没用。
它会是什么?
我尝试了
@ComponentScan
,更改了自动装配并更改了 Mapper 类上的注释。
您必须以 MapStruct 方式将其声明为 bean,而不是使用
@Component
:
@Mapper(componentModel = "spring")
public interface PriceEntityMapper {
现在只需用
@Autowired
初始化它,它将被创建为一个 bean。
否则,你必须直接声明映射器:
PriceEntityMapper mapper = Mappers.getMapper(PriceEntityMapper.class)
有关更多信息,请参阅 MapStruct 配置选项 ->
mapstruct.defaultComponentModel
部分的文档: