简体   繁体   English

为什么 RestController 在 Spring Boot 中不起作用?

[英]Why RestController doesn't work in Spring Boot?

I have Spring Boot Starter with a REST Controller working perfect:我有 Spring 启动器和 REST Controller 工作完美:

@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:但是,当我使用无限循环添加其他 Controller 时,REST Controller 不起作用:

Error: connect ECONNREFUSED 127.0.0.1:8080

It is a samle code of other Controller.它是其他 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.因此,其他 Controller(HelloWorld 类)始终有效,而 RestController(SimpleController 类)仅在其他 Controller 被禁用时才有效。 Why so?为什么这样?

To add to the accepted answer, you can use an implementation of CommandLineRunner or ApplicationRunner like要添加到已接受的答案,您可以使用CommandLineRunnerApplicationRunner的实现,例如

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.当 Spring 尝试创建 bean 实例、设置依赖关系和整个基础设施时,它开始了一个无限循环。 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.请注意,启动(大部分)在主线程上运行,并且您将其阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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