我从 0 开始我的第一个 api 项目。 我从 spring 初始化程序下载了启动项目,然后开始在其中编写代码。但现在我有一个小问题。似乎主类无法识别我创建的 Controller ,因为我尝试将 Controller 的代码放入主类中并且它可以工作,在实际状态下它给我“路径未找到404”错误。
我是否必须在某个地方添加 Controller ?
提前致谢!
主类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiDispatcherApplication {
public static void main(String[] args) {
SpringApplication.run(ApiDispatcherApplication.class, args);
}
}
Controller
import model.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class WebController {
@Autowired
public WebController(){
}
@RequestMapping(path = "/sample", method = RequestMethod.GET)
public ApiModel Sample(@RequestParam(value = "name", defaultValue = "Robot") String name){
ApiModel response = new ApiModel();
response.setResponse("Your name is " + name);
return response;
}
}
此时它给了我 404,但是如果我将 Controller 代码直接放在主类中,它就可以工作
最佳答案
谢谢@dassum,我用这种方式解决了我的问题:
主类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@ComponentScan("controller") //controller is the name of the folder of my controllers
public class ApiDispatcherApplication {
public static void main(String[] args) {
SpringApplication.run(ApiDispatcherApplication.class, args);
}
}
希望我通过这篇文章帮助了其他一些初学者:)
谢谢@dassum!
关于java - Spring API : the program is not finding the pat into the controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57010072/