IDE:Eclipse
新建maven工程
勾选Create a simple project(skip archetype selection)
配置POM
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
创建资源
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
创建资源控制器
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
@RequestMapping
确保到/greeing
的HTTP请求映射到greeting()
方法。@RequestMapping
默认映射所有的HTTP操作。可以使用@RequestMapping(method=GET)
限定映射@RequestParam
将请求参数name
绑定到greeting()
方法的name
参数。如果该值为空,则显示默认值World
。@RestController
是@Controller
和@ResponseBody
的简写
Greeting
必须要转成JSON对象。这不需要你手动去转换。因为Jackson 2
在classpath里,Spring会自动将Greeting
转换为JSON。
创建应用执行器
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication
有下面几个意思:
- @Configuration 定义这个类为bean
- @EnableAutoConfiguration 告诉Spring Boot 根据classpath设置、其他beans和各种设置加载bean
- @ComponentScan 告诉Spring在
hello
包中查找其他组件、配置、服务 - 一般来讲,你要加上
@EnableWebMvc
,但当classpath中有spring-webmvc时,Spring Boot会自动添加
测试服务
像启动普通工程那样启动。
访问http://localhost:8080/greeting
访问http://localhost:8080/greeting?name=Jzh