简体   繁体   English

在SpringBoot中的Controller中调用Rest API时出现404错误

[英]404 Error when invoke a Rest API in Controller in SpringBoot

I have develop a simple SpringBoot application with a rest end point as below, 我已经开发了一个简单的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);
    }
}

Above works fine and return 200 in when i invoke the rest end point as, http://localhost:8080/api/home 以上工作正常并在我以http:// localhost:8080 / api / home调用其余端点时返回200

But now i have move the rest end point to a different class as below, 但是现在我将其余的端点移到了一个不同的类,如下所示,

@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);
        }   
}

And the Example class looks like, 而且Example类看起来像

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

Now i invoke the end point i get below error, 现在我调用终点,我得到以下错误,

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

What am i missing here please? 我在这里想念什么?

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

Or also you can put the package of your controller in the main Application , something like this: 或者,您也可以将控制器的程序包放在主应用程序中,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM