从AbstractMessageHandler获取SpringAccess @Autowired服务
问题描述:
我有一个订阅了MQTT代理的SpringBootApplication。 MQTT消息需要保存到数据库,但我无法访问我的@Autowired服务。从AbstractMessageHandler获取SpringAccess @Autowired服务
例外,我得到:
Field deviceService in com.example.MqttMessageHandler required a bean of type 'com.example.service.DeviceService' that could not be found.
MQTTApiApplication.java
@SpringBootApplication(scanBasePackages = "{com.example}")
public class MQTTApiApplication {
public static void main(String[] args) {
SpringApplicationBuilder(MQTTApiApplication.class)
.web(false).run(args);
}
@Bean
public IntegrationFlow mqttInFlow() {
return IntegrationFlows.from(mqttInbound())
.handle(new MqttMessageHandler())
.get();
}
}
MqttMessageHandler.java
public class MqttMessageHandler extends AbstractMessageHandler {
@Autowired
DeviceService deviceService;
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
deviceService.saveDevice(new Device());
}
}
答
Application.java
@SpringBootApplication
public class MQTTApiApplication {
public static void main(String[] args) {
SpringApplication.run(MQTTApiApplication.class, args);
}
@Bean
public IntegrationFlow mqttinFlow(MqttMessageHandler handler) {
return IntegrationFlows
.from(mqttInbound())
.handle(handler).get();
}
}
MqqtMessageHandler.java
@Component
public class MqttMessageHandler extends AbstractMessageHandler{
@Autowired
private DeviceService deviceService;
@Override
protected void handleMessageInternal(String message) {
//...
}
}
DeviceService.java
@Service
public class DeviceService {
@Autowired
private DeviceRepository repository;
//...
}
DeviceController.java
@RestController
@RequestMapping("/")
public class DeviceController {
@Autowired
private IntegrationFlow flow;
//...
}
DeviceRepository.java
@Repository
public class DeviceRepository {
public void save() {
//...
}
}
是的,我已经添加@Component的符号,但仍然得到相同的错误。我通常从RestController访问服务。 – mkdeki
那么DeviceService呢? –
当我将DeviceService放入RestController时,我可以访问DeviceService(这是Autowired)。 问题是我无法从MqttMessageHandler访问Autowired服务/控制器。 – mkdeki