You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成MQTT DSL:通道自动装配失败及最佳发布方式咨询

Spring Integration MQTT集成:自动装配通道失败原因及最佳实践

一、现有实现与背景

我正在用Spring Boot结合Java DSL配置实现MQTT集成,目前通过定义MessageGateway的方式可以正常发布消息。

MQTT配置类代码

@Slf4j
@Configuration
@EnableIntegration
public class MqttJavaApplicationConfig {

    @Value( "${mqtt.broker.url}" )
    private String brokerUrl;

    @Bean
    public IntegrationFlow mqttOutFlow() {
        Mqttv5PahoMessageHandler messageHandler = new Mqttv5PahoMessageHandler(brokerUrl, "mqttv5SIout");
        MqttHeaderMapper mqttHeaderMapper = new MqttHeaderMapper();
        mqttHeaderMapper.setOutboundHeaderNames("some_user_header", MessageHeaders.CONTENT_TYPE);
        messageHandler.setHeaderMapper(mqttHeaderMapper);
        messageHandler.setAsync(true);
        messageHandler.setAsyncEvents(true);
        messageHandler.setDefaultTopic("testTopic");

        return f -> f.handle(messageHandler);
    }
}

MessageGateway实现

@MessagingGateway
public interface MqttProduceGateway {

    @Gateway(requestChannel = "mqttOutFlow.input")
    void publishToMQTT(String data);
}

消息发布服务类

@Getter
@Setter
@NoArgsConstructor
@Component
public class PublishService {

    @Autowired
    MqttProduceGateway mqttProduceGateway;
    

    public boolean publishToMqttBroker(String data){
        mqttProduceGateway.publishToMQTT(data);
        return  true;
    }

}

二、遇到的问题

为简化实现,我尝试直接注入mqttOutFlow.input通道来使用MessageHandler,代码如下:

@Slf4j
@ComponentScan(basePackages = { "de.diag.testprototypes.projectscv.mqtt.client"})
@IntegrationComponentScan
@SpringBootApplication
public class MqttJavaApplication {

    @Autowired
    @Qualifier("mqttOutFlow.input")
    private DirectChannel mqttOutFlowInput;

}

此时自动装配失败,报错信息为:
No qualifying bean of type 'org.springframework.integration.channel.DirectChannel' available:

但通过上下文手动获取可以成功拿到该Bean:

Object object =  context.getBean("mqttOutFlow.input");
log.info("type " + object.getClass().getName());

日志输出显示该Bean确实是DirectChannel类型:
2024-02-22T16:21:25.280+01:00 INFO 26304 --- [ main] d.k.d.t.p.m.client.MqttJavaApplication : type org.springframework.integration.channel.DirectChannel

三、咨询问题

  1. 为什么通过@Autowired + @Qualifier自动装配mqttOutFlow.input通道会失败?
  2. 使用Spring Integration发布MQTT消息的最佳方案是什么?

内容的提问来源于stack exchange,提问作者Christian V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 16:12:02