I have Spring Boot Starter with a REST Controller working perfect:
@RestController
public class SimpleController {
 @GetMapping("/") 
 public String helloWorld() {
 return "Hello world"; 
 }
}
However, when I add other Controller with infinite loop the REST Controller doesn't work:
Error: connect ECONNREFUSED 127.0.0.1:8080
It is a samle code of other Controller.
@Component 
public class HelloWorld {
 @Autowired
 public void hello() 
 {
 while(true) {
 System.out.println("Hello world!");
 Thread.sleep(12000);
 } 
 }
}
So, other Controller (HelloWorld class) is always working, while RestController (SimpleController class) works only if other Controller is disabled. Why so?
2 Answers 2
To add to the accepted answer, you can use an implementation of CommandLineRunner or ApplicationRunner like
package com.example.restservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CommandRunner implements CommandLineRunner {
 @Autowired
 private HelloWorld helloWorld;
 @Override
 public void run(String... args) throws Exception {
 while (true) {
 System.out.println("Hello world!" + helloWorld);
 Thread.sleep(12000);
 }
 }
}
4 Comments
@Scheduled method so you don't have an infinite loop code smell?That's because your application never start properly. While Spring try to create the bean instances, set up dependencies and the whole infrastucrures, it start an infinite loop. It stuck on that, so your server never finish to starts, application context never setup. Note that the startup (mostly) runs on the main thread, and you block it.