java - Spring API : the program is not finding the pat into the controller

标签 java api spring-boot gradle intellij-14

我从 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/

相关文章:

java - 在 Java 中创建一个新线程有多昂贵?我们什么时候应该考虑使用线程池?

java - Java 类中允许的最大代码行数?

python - 修改现有代码以从API获取搜索结果

javascript - 使用 openexchangerates API 使用 JS/JQuery 进行货币转换

android - android 中的 MediaRecorder.pause()

java - Spring Boot 不替换 application.properties 文件中的环境变量

Java 控制面板 - 更新选项卡不断加载

java - 按序数选择枚举; java

spring-boot - 我使用@Sql进行Spring Test时发生FileNotFoundException

java - 如何使用数据库数据动态添加或删除spring框架的调度程序(服务器处于运行状态)?