简体   繁体   中英

Why RestController doesn't work in Spring Boot?

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?

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);
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM