我有下一个映射器:
@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 {
否则,你必须使用:而不是使用依赖注入:
PriceEntityMapper mapper = Mappers.getMapper(PriceEntityMapper.class)