【问题标题】:404 Error when invoke a Rest API in Controller in SpringBoot在 Spring Boot 中调用 Controller 中的 Rest API 时出现 404 错误
【发布时间】:2015-11-01 11:07:04
【问题描述】:

我已经开发了一个简单的 SpringBoot 应用程序,其休息端点如下,

@SpringBootApplication
@RestController
@RequestMapping(value = "/api")
public class Example {

   @RequestMapping(value="/home", method = RequestMethod.GET)
    HttpEntity<String>  home() {
        System.out.println("-----------myService invoke-----------");
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }
}

当我调用其余端点时,以上工作正常并返回 200, http://localhost:8080/api/home

但现在我已将其余端点移至如下不同的类,

@RestController
@RequestMapping(value = "/api")
public class MyController {

     @RequestMapping(value="/home", method = RequestMethod.GET)
        HttpEntity<String>  home() {
            System.out.println("-----------myService invoke-----------");
            return new ResponseEntity<String>(HttpStatus.OK);
        }   
}

Example 类看起来像,

@SpringBootApplication
public class Example {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }
}

现在我调用我得到以下错误的端点,

{
  "timestamp": 1446375811463,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/api/home"
}

请问我在这里缺少什么?

【问题讨论】:

  • MyControllerExample在同一个包或子包中吗?

标签: java spring spring-boot


【解决方案1】:

请将类、MyController 和 Example 放在同一个包中,然后重试

【讨论】:

    【解决方案2】:

    或者您也可以将控制器的包放在主应用程序中,如下所示:

    @SpringBootApplication
    @EnableAutoConfiguration
    @ComponentScan(basePackages={"com.controller"})
    public class Application
    

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2019-02-20
      • 2019-07-05
      • 2015-04-10
      • 2021-12-18
      • 1970-01-01
      • 2020-04-12
      • 2021-12-20
      • 2017-11-08
      相关资源
      最近更新 更多