[英]Why RestController doesn't work in Spring Boot?
我有 Spring 启动器和 REST Controller 工作完美:
@RestController
public class SimpleController {
@GetMapping("/")
public String helloWorld() {
return "Hello world";
}
}
但是,当我使用无限循环添加其他 Controller 时,REST Controller 不起作用:
Error: connect ECONNREFUSED 127.0.0.1:8080
它是其他 Controller 的示例代码。
@Component
public class HelloWorld {
@Autowired
public void hello()
{
while(true) {
System.out.println("Hello world!");
Thread.sleep(12000);
}
}
}
因此,其他 Controller(HelloWorld 类)始终有效,而 RestController(SimpleController 类)仅在其他 Controller 被禁用时才有效。 为什么这样?
要添加到已接受的答案,您可以使用CommandLineRunner
或ApplicationRunner
的实现,例如
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);
}
}
}
那是因为您的应用程序永远无法正常启动。 当 Spring 尝试创建 bean 实例、设置依赖关系和整个基础设施时,它开始了一个无限循环。 它坚持下去,所以你的服务器永远不会完成启动,应用程序上下文永远不会设置。 请注意,启动(大部分)在主线程上运行,并且您将其阻止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.