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

时间:2015-11-01 11:07:04

标签: java spring spring-boot

我开发了一个简单的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"
}

我在这里想念的是什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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