文章目的
本篇文章介绍如何创建使用Spring创建一个Hello World的RESTful web service
该服务可以通过
http://localhost:8080/greeting
访问,返回JSON字符串
{"id":1,"content":"Hello, World!"}
你还可以在查询URL中自己定义name, 比如
http://localhost:8080/greeting?name=User
应用会覆盖默认值World,返回
{"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
或者新建MAVEN项目,复制粘贴教程内的代码
MAVEN项目的包结构(GRADLE略)
└── src
└── main
└── java
└── hello
pom.xml文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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 提供了下列功能:
1. 整合所有的JAR包,形成über-jar
2. 搜索
public static void main(),作为可执行的类
3. 设置了
Spring Boot 依赖包的版本号
试验步骤
- 新建src/main/java/hello/Greeting.java
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;
}
}
Spring利用内置的
Jackson JSON库自动把Greeting类变成了JSON字符串
2. 新建控制器
src/main/java/hello/GreetingController.java
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合体。
3. 创建可执行的类
src/main/java/hello/Application.java
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
@EnableAutoConfiguration
@EnableWebMvc
@ComponentScan
我们不需要任何的web.xml文件就能运行。
4. 运行程序
跟运行普通的JAVA程序一样,运行后,直接访问
http://localhost:8080/greeting
或者
http://localhost:8080/greeting?name=User
可以看到结果。
简单吧?
注意:
本人用IntelliJ的时候,发现pom的包不下载,用eclipse可以下载。具体怎么解决,还没找到办法。
一定要把JRE设置为1.8,否则会报错。