gpt4 book ai didi

java - 在为 mapstruct 制作的抽象类中 Autowiring

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:46 26 4
gpt4 key购买 nike

我正在尝试使用 Spring 构建一个 REST Controller 。为了格式化数据以提高可读性和集成度,我使用了 Mapstruct。这是我编写 Mapper 的方式。

@Mapper
public abstract class DeviceDataMapper {

@Autowired
DeviceService deviceService;

public static DeviceDataMapper INSTANCE = Mappers.getMapper(DeviceDataMapper.class);

@Mappings({
@Mapping(source = "deviceId", target = "iddevice"),
@Mapping(source = "deviceName", target = "name")
})
public abstract TODevice deviceToTODevice(DeviceData device);

public DeviceData toDeviceToDeviceData(TODevice toDevice){
DeviceData deviceData = new DeviceData();
deviceData.setDeviceId(toDevice.getIddevice());
deviceData.setDeviceName(toDevice.getName());
deviceData.setDeviceTemplateId(toDevice.getDeviceTemplateId());
try {
deviceData.setDeviceTemplateName(deviceService.findDeviceTemplateById(toDevice.getDeviceTemplateId()).getName());
} catch (Exception e) {
e.printStackTrace();
}

return deviceData;
}}

API Controller 函数如下所示

@RequestMapping(value = "/{deviceId}",method = RequestMethod.GET)
public @ResponseBody DeviceData get(@PathVariable int deviceId) {
DeviceData deviceData=new DeviceData();
try {
deviceData = DeviceDataMapper.INSTANCE.toDeviceToDevice(deviceService.findOne(deviceId));
} catch (Exception e) {
e.printStackTrace();
}
return deviceData;
}

除了一个细节外,输出设备数据返回正常。我无法进入此函数抽象类中 Autowiring 资源的可访问性?还是我实例化的方式使这个函数无法访问?我应该改变什么才能让它工作?我也尝试过 @Inject from javax.inject 具有相同的结果。

最佳答案

您可以使用 Spring 作为映射器的组件模型:

@Mapper(componentModel="spring")
public abstract class DeviceDataMapper {
...
}

通过这种方式,您可以将依赖项注入(inject)其中(例如,它使用的其他手写代码)以及将映射器注入(inject)其他类,而不是求助于 INSTANCE 模式。

关于java - 在为 mapstruct 制作的抽象类中 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30120838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com