本篇文章介绍如何创建使用Spring创建一个Hello World的RESTful web service
该服务可以通过
http://localhost:8080/greeting
{"id":1,"content":"Hello, World!"}
http://localhost:8080/greeting?name=User
{"id":1,"content":"Hello, User!"}
IDE
JDK 1.8 以上
Gradle 2.3+ 或 Maven 3.0+
从https://github.com/spring-guides/gs-rest-service/archive/master.zip处下载包,或者使用git命令
git clone https://github.com/spring-guides/gs-rest-service.git
└── src └── main └── java └── hellopom.xml文件
4.0.0
org.springframework
gs-rest-service
0.1.0
org.springframework.boot
spring-boot-starter-parent
1.3.3.RELEASE
org.springframework.boot
spring-boot-starter-web
1.8
org.springframework.boot
spring-boot-maven-plugin
spring-releases
https://repo.spring.io/libs-release
spring-releases
https://repo.spring.io/libs-release
Spring Boot Maven plugin 提供了下列功能:
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));
}
}
@RestController,
它相当于@Controller和@ResponseBody合体。
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); } }注意: