Reputation: 41
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?
Upvotes: 1
Views: 1310
Reputation: 8213
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);
}
}
}
Upvotes: 1
Reputation: 2047
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.
Upvotes: -1