0

I am trouble with accessing my service to save data in a class.

I have a class and wish to use my defined service that works well in my RestController by am struggling to access it in custom class.

I wish to do something like the following new MessageProcessor.processMessage(message) --> this should access service and save the data to database.

@Controller
public class MessageProcessor {

    @Autowired
    private IOTService iotService;

    public MessageProcessor() {

    }

    public void processMessage(String message) {
        iotService.addMessage(message);
    }
}

It is being called like this in a random class. The Autowired annotion is not working as i expected.

new MessageProcessor().processMessage("test");

I am new to Spring so any suggestions would be appreciated

  • 1
    I think you fundamentally misunderstand controllers and how the autowired annotation works. Read up on Spring Beans, what they are, and how Controllers are instantiated. – John Kim Nov 21 '19 at 04:31
  • IOTService should be a valid Spring bean. Please share code of IOTService class and spring boot main class. – Smile Nov 21 '19 at 04:33
  • IOTService add @service Annoation at class level then it will work – harkesh kumar Nov 21 '19 at 07:42

1 Answers1

0

First of all, you need to understand how the framework work. I am giving an example, may be it clears some of your doubts and logic.

The autowiring works in a way like, you have to follow a standard :

  1. Make a domain class (Domain.class).
  2. Make a controller (DomainController.class)(if there is need), mark it with annotation @Controller.
  3. Make a service class,(DomainService.class), mark it with annotation @Service

In this way, you can use autowiring concept. If you want to use your service class method outside this class hierarchy, you have create its new instance with new keyword i.e. new DomainService() The thing to be noted here autowiring works within a specific model not everywhere.

ASK
  • 1,136
  • 1
  • 10
  • 14