gpt4 book ai didi

java - Spring Boot应用程序错误页面

转载 作者:行者123 更新时间:2023-12-01 18:07:42 24 4
gpt4 key购买 nike

我开始学习 Spring Boot,并且正在学习 YouTube 上的教程。然而,我的项目中发生了一件奇怪的事情。我刚刚创建了一个名为 GreetingController 的 Controller 。下面是该类的完整代码

@RestController
@EnableAutoConfiguration
public class GreetingController {

private static BigInteger nextId;

private static Map<BigInteger, Greeting> greetingMap;

private static Greeting save(Greeting greeting) {
if (greetingMap == null) {
greetingMap = new HashMap<BigInteger, Greeting>();
nextId = BigInteger.ONE;
}
greeting.setId(nextId);
nextId = nextId.add(BigInteger.ONE);
greetingMap.put(greeting.getId(), greeting);
return greeting;
}

static {
Greeting g1 = new Greeting();
g1.setText("Hello World");
save(g1);

Greeting g2 = new Greeting();
g2.setText("Hola Mundo");
save(g2);
}

@RequestMapping(value = "/api/greetings", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Greeting>> getGreetings() {

Collection<Greeting> greetings = greetingMap.values();

return new ResponseEntity<Collection<Greeting>>(greetings,
HttpStatus.OK);

}

}

Controller 位于以下包下:

enter image description here

但是,当我使用 URL http://localhost:8080/api/greetings 引导应用程序时,我的页面上会出现以下错误:

enter image description here

但是,当我将 GreetingController 放在 Application 类的同一个包中时,如下图所示:

enter image description here

然后获取相同的 URL http://localhost:8080/api/greetings,我得到了正确的响应:

enter image description here

谁能解释一下为什么?

最佳答案

将您的com.example包重命名为org.example。当您放置 @SpringBootApplication 注解时,Spring Boot 会扫描 Controller 类包的所有子包。

或者将@ComponentScan("org.example")放在同一个类上。这样你就可以告诉 spring boot 在哪里搜索你的 Controller (和其他 bean)。

关于java - Spring Boot应用程序错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com