spring Boot 学习第一步,就是初始化项目和来一个hello world的api。java
访问 http://start.spring.io/ 来初始化一个spring boot项目,生成的项目中包含最基本的 pom依赖项目。web
在pom.xmlspring
添加如下依赖:数据库
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在建立好的包里就有DemoApplication.java 类,这是springboot的入口类。
@SpringBootApplication注解全局惟一api
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
在这个类上能够添加springboot
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) @EnableScheduling
来暂时停用对数据库的访问,以及启用任务管理。restful
接下来就是编写咱们的控制层了,也就是处理http请求的。app
@RestController public class HelloController { private final AtomicLong counter = new AtomicLong(); @RequestMapping("/hello") public Person hello() { return new Person(counter.incrementAndGet(),"4321"); } @RequestMapping(value="/newWorld", method = RequestMethod.GET) public String newWorld() { return "Hello New43 da World"; } }
@RestController声明这是一个restful API 的控制器,直接返回JSON串;@RequestMapping能够用来指定请求的地址和请求方法(GET/POST/PUT)spring-boot
@Controller public class FileUploadController { @GetMapping("/resTest") @ResponseBody public Person resTest() { return new Person(3674,"fdasfa"); } @PostMapping("/resTest") @ResponseBody public Person resTest() { return new Person(3674,"fdasfa"); } }
@Controller + @ResponseBody 一样能够产生 @RestController的效果。
@PostMapping和@GetMapping 看名字就知道是对应不一样的请求方法。学习