使用springboot集成mqtt的坑

starlin 4,221 2022-05-09

最近在项目中使用到了mqtt,引入springboot的相关依赖后,发现怎么都无法注入对应的service,相应的代码如下:

引入相关starter

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-mqtt</artifactId>
</dependency>

定义接口

@Component
@MessagingGateway(defaultRequestChannel = "mqttOutChannel")
public interface MqttPushService {
    @MqttLog
    void pushMessage(String data, @Header(MqttHeaders.TOPIC) String topic);

}

在需要的地方注入接口

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestFeginConsumer {
    @Autowired
    private MqttPushService mqttPushServer;

    @Test
    public void test() {
        mqttPushServer.pushMessage(null,null);
    }
}

运行的上述代码提示,如下错误信息:

Action:
Consider defining a bean of type 'com.xxxx.xxxx' in your configuration

反正就是提示该bean未注入,实在是想不明白,怎么就未注入了,后面的翻看@MessagingGateway注解的文档,发现问题了

解决方案

关于@MessagingGateway注解,相关文档请点击

其中有这么一句话标注为important,如下图所示:

大概的意思就是,使用普通的注解@CompontenScan是无法扫描@MessagingGateway注解,需要使用@IntegrationComponentScan注解和@Configuration注解

至此完美解决了,真不明白网上的那些文章,吵来吵去的,都没测试过了么

the end ,感谢阅读!!!


# springboot