用于Spring集成消息处理程序的Bean注入

时间:2019-02-19 10:41:53

标签: spring spring-integration

我对Spring和Spring整合还很陌生。我正在尝试做的事情:使用Spring集成发布mqtt消息。

代码如下:

@Configuration
@IntegrationComponentScan
@Service
public class MQTTPublishAdapter {
private MqttConfiguration mqttConfiguration;

public MQTTPublishAdapter(MqttConfiguration mqttConfiguration) {
    this.mqttConfiguration = mqttConfiguration;
}
@Bean
public MessageChannel mqttOutboundChannel() {
  return new PublishSubscribeChannel();
}

@Bean
public MqttPahoClientFactory mqttClientFactory() {
    DefaultMqttPahoClientFactory factory = new 
        DefaultMqttPahoClientFactory();

 //... set factory details

    return factory;
}

@Bean
@ServiceActivator(inputChannel = "mqttOutboundChannel")
public MQTTCustomMessageHandler mqttOutbound() {
    String clientId = UUID.randomUUID().toString();
    MQTTCustomMessageHandler messageHandler =
        new MQTTCustomMessageHandler(clientId, mqttClientFactory());

//...set messagehandler details

    return messageHandler;
}

//I extend this only because the publish method is protected and I want to 
send messages to different topics
public class MQTTCustomMessageHandler extends MqttPahoMessageHandler {
//default constructors

public void sendMessage(String topic, String message){
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload(message.getBytes());

    try {
        super.publish(topic, mqttMessage, null);
    } catch (Exception e) {
        log.error("Failure to publish message on topic " + topic, 
            e.getMessage());
        }
    }
}

这是我试图注入处理程序的地方

@Service
public class MQTTMessagePublisher {

private MQTTCustomMessageHandler mqttCustomMessageHandler;

public MQTTMessagePublisher(@Lazy MQTTCustomMessageHandler 
                                    mqttCustomMessageHandler) {
    this.mqttCustomMessageHandler = mqttCustomMessageHandler;
}

    public void publishMessage(String topic, String message) {
        mqttCustomMessageHandler.sendMessage(topic, message);
    }
}

所以我的问题是我应该如何注入要使用的bean,因为如果删除@Lazy批注,它将说“正在创建请求的bean:是否存在不可解析的循环引用?”。我没有任何循环依赖项,因为在Bean中我只设置了一些字符串,所以我猜测我并不真正理解它应该如何工作。

非常抱歉格式化,这是我在这里遇到的第一个问题。

编辑:

如果我删除

@ServiceActivator(inputChannel = "mqttOutboundChannel")

并添加

messageHandler.setChannelResolver((name) -> mqttOutboundChannel());

有效。我仍然不清楚为什么代码会崩溃。

1 个答案:

答案 0 :(得分:0)

您显示了很多自定义代码,但不是全部。 在仅是自定义代码的地方很难回答问题。分享尽可能多的信息将是很棒的。例如,在GitHub上让我们玩和复制的外部项目将完全有帮助,并且可以节省一些时间。

尽管如此,我想知道您的MQTTCustomMessageHandler是什么。但是我猜它不是MessageHandler的实现。从这里开始,@ServiceActivator注释将无法正常工作,因为它实际上是为mqttOutbound()应用的,而不是您期望的。或者,您需要将此注释移至sendMessage()中的MQTTCustomMessageHandler方法中,或将其作为MessageHandler

另一方面,由于您是从@ServiceActivator手动调用该方法的,所以根本不知道为什么需要MQTTMessagePublisher注释。

同样不清楚的是,当Framework提供开箱即用的通道适配器实现时,为什么会有如此多的自定义代码。

您的代码中的问题太多,无法回答...

请参阅参考手册中的更多信息:

https://docs.spring.io/spring-integration/docs/current/reference/html/#annotations

https://docs.spring.io/spring-integration/docs/current/reference/html/#mqtt