Spring - 从 AbstractMessageHandler 访问 @Autowired 服务

Spring - access @Autowired service from AbstractMessageHandler

我有一个订阅 MQTT 代理的 SpringBootApplication。 MQTT 消息需要保存到数据库,但我无法访问我的@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() {
        //...
    }
}