Home > front end >  Cannot Autowiring Spring MQTT
Cannot Autowiring Spring MQTT

Time:05-15

Spring 2.5.3 and Java 1.8

I want to send a json data to a mqtt topic but i cannot autowiring my Interface and i'm getting null pointer exception when i try with no autowiring.

When i try it this message shows up;

Could not autowire. No beans of 'MqttGateway' type found. 
 Inspection info:
Reports autowiring problems on injection points of Spring beans:

My Controller;

    package com.example.mqtt.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.example.mqtt.MqttGateway;
    
    
    
    @RestController
    public class MqttController {
    
        @Autowired
        MqttGateway mqttGateway;
    
        @PostMapping("/sendMessage")
        public ResponseEntity<?> publish(@RequestBody String mqttMessage){
    
            try {
                JsonObject convertObject = new Gson().fromJson(mqttMessage, JsonObject.class);
                mqttGateway.senToMqtt(convertObject.get("message").toString(), convertObject.get("topic").toString());
                return ResponseEntity.ok("Success");
            }catch(Exception ex) {
                ex.printStackTrace();
                return ResponseEntity.ok("fail");
            }
        }
    
    }

My Interface;

package com.example.mqtt;

import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;

@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {

    void senToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic);

}

CodePudding user response:

You have to annotate your interface with and also the class with to make it work:

package com.example.mqtt;

import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.example.mqtt.MqttGateway;

public interface MqttGateway {

    void senToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic);

}

CodePudding user response:

Another Problem :

When I remove the autowired annotation this error message shows up ;

java.lang.NullPointerException: Cannot invoke "com.aiotico.MqttGateway.senToMqtt(String, String)" because "this.mqttGateway" is null

at com.aiotico.controller.MqttController.publish(MqttController.java:23)

But how can my interface can be null ?

  • Related