2017-10-20 85 views
0

我有一個訂閱了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()); 
    } 
} 

回答

0

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() { 
     //... 
    } 
} 
+0

是的,我已經添加@Component的符號,但仍然得到相同的錯誤。我通常從RestController訪問服務。 – mkdeki

+0

那麼DeviceService呢? –

+0

當我將DeviceService放入RestController時,我可以訪問DeviceService(這是Autowired)。 問題是我無法從MqttMessageHandler訪問Autowired服務/控制器。 – mkdeki