Nav*_*een 15 java rest spring spring-mvc spring-boot
我已经创建了演示Spring Boot项目并实现了Restful服务,如下所示
@RestController
public class GreetingsController {
@RequestMapping(value="/api/greetings", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getGreetings(){
return new ResponseEntity<String>("Hello World", HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用Postman工具调用带有URL" http:// localhost:8080/api/greetings "作为请求方法GET的服务时,我收到以下错误消息
{
"timestamp": 1449495844177,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/api/greetings"
}
Run Code Online (Sandbox Code Playgroud)
Per Spring Boot应用程序,我不必在web.xml中配置Spring Dispatcher servlet.
有人可以帮我找出这里遗漏的地方吗?
你可能错过了@SpringBootApplication
:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
@SpringBootApplication
包括@ComponentScan
扫描包所在的包和所有儿童包.您的控制器可能不在其中任何一个.
三种可能的解决方案:
1)确保具有@Controller的YourController.java文件和具有@SpringBootApplication的YourSpringBootFile.java文件位于同一软件包中。
所以,您知道我在说什么,这是我的WebController.java文件:
@RestController
public class WebController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping(value= "/hi", method = RequestMethod.GET)
public @ResponseBody Greeting sayHello(
@RequestParam(value = "name", required = false, defaultValue = "Stranger") String name) {
System.out.println("Inside sayHello() of WebController.java");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的JsonPostExampleProj1Application.java:
@SpringBootApplication
public class JsonPostExampleProj1Application {
public static void main(String[] args) {
SpringApplication.run(JsonPostExampleProj1Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
2)如果您希望控制器位于YourSpringBootFile.java包之外的其他包中,请遵循以下说明= Spring:在应用程序主方法中运行多个“ SpringApplication.Run()”
3)尝试在Controller类的顶部使用@RestController而不是@Controller。
这可以帮助某人,就像我的情况一样。
确保控制器的包名称是 Spring 主方法包的派生(或子)包。
例如:
如果 main 方法包是,com.company.demo.example
那么控制器包应该是这样的com.company.demo.example.controller
(如果你指定了类似的东西,com.company.demo.controller
它就行不通了!)。
我刚刚遇到这个错误,上面的解决方案都不适合我,所以我添加了另一个可能的东西,也许你也可能会错过,确保你@ResponseBody
的方法有注释。
@RequestMapping(value="/yourPath", method=RequestMethod.GET)
@ResponseBody
public String exampleMethod() {
return "test";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42669 次 |
最近记录: |