【发布时间】:2023-02-24 21:53:02
【问题描述】:
按照教程,我第一次尝试同时使用 java 和 Spring Boot。
我在一个名为 User 的包中创建了一个名为 UserController 的类,我在其中定义了一个端点,UserController.java 的内容:
package com.example.demo.user;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(path = "/api/v1/user")
public class UserController {
@GetMapping("/")
public List<User> hello() {
User myUser = new User(5000, 1, 1);
return List.of(myUser);
}
}
User 包还包括 User.java 中名为 User 的类,以及 User 类的 getter、setter 和构造函数。
在与用户包相同的层次结构中,我有包含以下内容的 DemoApplication.java:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
我期待收到诸如 [User] ......之类的响应,但是我收到 404 not found。
this 是我的项目结构的样子
我在这里做错了什么?搜索了很多没有找到答案。
提前谢谢你的帮助。
当我修改代码以便在 DemoApplication.java 中定义终点时:
package com.example.demo;
import com.example.demo.user.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@SpringBootApplication
@RestController
@RequestMapping(path = "/api/v1/user")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/")
public List<User> hello() {
User myUser = new User(5000, 1, 1);
return List.of(myUser);
}
}
端点开始按预期工作。 但我期待它继续给出 404,因为我没有做任何根本不同的事情。
这是我使用邮递员发送 GET 请求的端点: http://localhost:8080/api/v1/user/
【问题讨论】:
-
我看不出有什么不对。这可能是您的 IDE 在捉弄您。如果您从命令行运行应用程序(例如通过运行
.\mvnw spring-boot:run)会发生什么? -
@g00glen00b 同样的结果
-
您可以在主类之上尝试 @ComponentScan(basePackages = {"com.example.demo"}) 。
标签: java spring-boot